我正在尝试过滤ngFor中的数组。如果我执行以下操作,则会出现错误:
.html:
<div *ngFor="let group of filterGroups(report.assetGroups)">
错误: 无法读取未定义的属性"资产组"。
如果我执行以下操作,则会出现另一个错误:
.html:
<div *ngFor="let group of filterGroups(report?.assetGroups)">
错误:
技术经理报告组件.html:66 错误类型错误: _co.filterGroups 不是函数
所以我有点坚持如何进行过滤。这是我的过滤函数:
filterGroups(itemList: AssetGroup[]): AssetGroup[] {
let result: AssetGroup[] = [];
return result;
}
请注意,ngFor 在没有过滤器功能的情况下可以完美运行。
我的初始化方法:
ngOnInit() {
this.route.params.subscribe( params => {
this.reportId = params.reportId;
this.apiService.getReportComplete(this.reportId).subscribe((data) => {
this.report = data;
this.loadGraph(this.report);
});
});
}
和服务:
getReportComplete(reportId:string):Observable<ReportComplete>{
var url = `https://xxx.azurewebsites.net/api/reportcomplete/${reportId}`;
return this.httpClient.get<ReportComplete>(url).pipe(
map(x => new ReportComplete(x)));
}
<ng-container *ngIf="report">
<div *ngFor="let group of filterGroups(report.assetGroups)">{{group}}</div>
</ng-container>
使用提供的代码,您可以在某个请求后将某些内容分配给report
属性,因此最初可能是undefined
或null
- 让我们添加检查。
由于filterGroups
正确处理null
参数,因此您可以测试是否定义了report
,如果未定义,则传递null
:
*ngFor="let group of filterGroups(report ? report.assetGroups : null)"
请注意,带有安全导航运算符的原始代码也应该有效:
*ngFor="let group of filterGroups(report?.assetGroups)"
请参阅此堆栈闪电战以获取演示。