【问题标题】:ionic 2 error on pipe filter (TypeError: Cannot read property 'filter' of undefined)管道过滤器上的 ionic 2 错误(TypeError:无法读取未定义的属性“过滤器”)
【发布时间】:2017-06-27 01:19:33
【问题描述】:

您好,我正在使用 ionic 2( version released 2.0)angular 2( version core 2.2.1) 尝试制作数组管道过滤器,但它总是显示错误 无法读取未定义的属性“过滤器”

import { Pipe ,PipeTransform } from '@angular/core';
 @Pipe({ name: 'fetch', pure: false }) 
export class Search implements PipeTransform { 

 transform(items:Array, conditions:{[field:string]:any}):Array { 
   return items.filter(item => { for (let field in conditions) { 
       if (item[field] !== conditions[field]) { 
         return false; 
       } 
      } 
      return true; 
   }); 
 } 
}

HTML

`<ion-content>
<ion-searchbar [(ngModel)]="term" [showCancelButton]="true"></ion-searchbar> 
      <ion-grid class="category">
      <ion-row text-center wrap>
        <ion-col width-33 *ngFor="let d of total|fetch:term">
<p> {{d.name}} </p>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>`

JSON responce code in total array [{id:1 ,name:"abc" },{id:2 ,name:"xyz" }]

【问题讨论】:

  • 将代码添加到问题中..不要评论..
  • 我正在创建一个数组搜索过滤器,它以任何方式显示此错误我如何在 ionic 2 中制作数组搜索过滤器
  • 可以加html端吗?
  • 我也认为应该是items:any[] 而不是items:Array
  • 你可以更新问题..不能真正查看评论部分的代码

标签: angular ionic2


【解决方案1】:

尝试猜测,因为您的代码不完整。

您是否使用 http 请求来获取数据?因为在这种情况下,您必须先以这种方式检查项目:

 if (items==null) {
        return null;
    }

完整代码:

transform(items: Array<any>, conditions: {[field: string]: any}): Array<any> {
    if (items==null) {
        return null;
    }

    return items.filter(item => {
        for (let field in conditions) {

            if (item[field] !== conditions[field]) {
                return false;
            }
        }
        return true;
    });
}

然后在 html 部分,如果您尝试过滤 {{d.name}},根据您的管道,我认为您必须编写如下内容:

*ngFor="let d of total|fetch:{name:term}"

希望有帮助

【讨论】:

  • 错误已消失,但搜索结果无效.. 总数组中的 JSON 响应代码 [{id:1 ,name:"abc" },{id:2 ,name:"xyz" }]
猜你喜欢
  • 2020-10-22
  • 1970-01-01
  • 2021-12-26
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2020-01-12
  • 1970-01-01
相关资源
最近更新 更多