我正在尝试以 Angular 创建一个搜索页面,该页面通过 Angulars $http 服务查询结果并返回一个定义的对象。代码看起来类似于 Angular 文档的教程:https://angular.io/tutorial/toh-pt6#final-code-review .
但是我的应用有几个关键的区别:
- 返回的对象是一个包含数组的对象,而不仅仅是一个数组。
- 我在 View 中的表遍历对象内的数组。
这给我带来了一个问题,即遍历此数组的 View 中的表在搜索任何内容之前抛出“空”错误,因此导致整个页面无法正常运行
<tbody>
<tr *ngFor="let email of (SearchResults$ | async).hits">
<td><input type="checkbox" (change)="changeSelectedEmailsMap(email)" ></td>
<td>{{email._source.from}}</td>
<td>{{email._source.recipient}}</td>
<td>{{email._source.date | date: 'dd/MM/yyyy hh:mm:ss'}}</td>
<td>{{email._source.subject}}</td>
<td><a routerLink="/detail/{{email.id}}" class="btn btn-outline-info btn-sm" role="button">View</a></td>
</tr>
</tbody>
目前,这是页面唯一使用这些结果的部分,但是它将使用 SearchResults$ 中的其他变量
我曾尝试完全隐藏表格,直到结果出现,在整个表格上使用 *ngIf="SearchResults$ !== null"。然而,一旦结果出现并且表格显示出来,它仍然会抛出一个空错误,这让我相信在表格开始观察之前对象没有被完全填满。
有什么方法可以让表只在变量存在时检查命中?
组件.ts:
export class RepositorySearchComponent implements OnInit {
@Input() repository: Repository;
SearchResults$: Observable<EmailSearchResult>;
private searchTerms = new Subject<string>();
constructor(private emailService: EmailService) { }
search(term: string){
this.searchTerms.next(term);
}
ngOnInit() {
this.SearchResults$ = this.searchTerms.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term: string) => this.emailService.search(term, this.repository.id))
);
}
}
最佳答案
按如下方式使用安全导航运算符:
<td>{{email?._source?.from}}</td>
注意这里使用的两个运算符,一个在 email
之后另一个在_source
之后
在所有 <td>
上使用安全导航运算符使用异步数据的标签。
关于angular - 无法在Angular中可观察到的Async中遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185543/