我有一个像这样的json
[{
"id": 9156,
"slug": "chicken-seekh-wrap",
"type": "dish",
"title": "Chicken Seekh Wrap",
"cuisine_type": [2140]
},
{
"id": 9150,
"slug": "green-salad",
"type": "dish",
"title": "Green Salad",
"cuisine_type": [2141]
}]
我创建了一个像这样的管道来按 angular2 中的美食类型进行过滤
@Pipe({
name: 'filter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(list: Array<any>, searchTerm: any): Array<any> {
if(!searchTerm) return list;
else {
return list.filter(item => item.cuisine_type[0] == searchTerm);
}
}
}
在 View 中我是这样使用的
<li *ngFor="let dish of dishes | filter : 2140">
<h2>{{dish.title}}</h2>
<input type="checkbox" [formControlName]="dish.id" />
</li>
但是它给了我这样的错误
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'filter' of undefined
TypeError: Cannot read property 'filter' of undefined
at FilterPipe.transform (filter.ts:20)
at checkAndUpdatePureExpressionInline (core.es5.js:11241)
at checkAndUpdateNodeInline (core.es5.js:12096)
at checkAndUpdateNode (core.es5.js:12058)
at debugCheckAndUpdateNode (core.es5.js:12687)
at debugCheckDirectivesFn (core.es5.js:12628)
at Object.View_FourthStepPage_1.currVal_0 [as updateDirectives] (FourthStepPage.html:26)
我不明白我到底做错了什么。请帮忙。谢谢。
最佳答案
首先,从 *ngFor 末尾删除不必要的 ')'。 其次,发生错误是因为您将 null 传递给过滤器。 过滤器尝试在 null 上运行,并且因为您尝试过滤 null,所以会弹出错误。 我的建议是添加检查传递的值是否有效。尝试将管道更改为:
@Pipe({
name: 'filter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(list: Array<any>, searchTerm: any): Array<any> {
if(!list)
return [];
if(!searchTerm) return list;
else {
return list.filter(item => item.cuisine_type[0] == searchTerm);
}
}
}
通过这种方式,您可以避免解析未定义的值..
附注 如果您的数据是从远程服务器获取的,并且盘中保存的数据是可观察的,那么您还必须使用异步管道。
关于javascript - Angular 2 管道返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45037452/