我有一个像这样的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);
        }
     }
 }


在视图中,我已经这样使用它

<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);
        }
     }
 }


这样,可以避免解析未定义的值。

压力
如果您的数据是从远程服务器获取的,并且餐具可以观察到,那么您也必须使用异步管道。

09-25 18:38
查看更多