【问题标题】:Angular2: Error while using a text filter pipe to filter an arrayAngular2:使用文本过滤器管道过滤数组时出错
【发布时间】:2017-05-13 16:38:13
【问题描述】:

我希望能够通过对类别名称执行搜索来搜索 categories 数组。我尝试了以下解决方案,但我不确定如何编辑管道中的变量以满足我的需要。

使用以下代码,控制台会记录以下错误。

categories.component.html:46:10 原因:item.indexOf 不是函数

Template

<tr *ngFor="let category of categories | textFilter:filterText">
    <td>{{category.name}}</td>
    <td>{{category.slug}}</td>
</tr>

Pipe

@Pipe({ name: 'textFilter' })

export class TextFilterPipe
{
  transform(value: any, term: any) {
    if (!term) return value;
    return value.filter((item: any) => item.indexOf(term) > -1);
  }
}

【问题讨论】:

  • 您是否尝试在 google 控制台中调试并检查哪些方法项为您公开?
  • 我不知道该怎么做..
  • return value.filter之前添加console.log(value);...`

标签: angular angular2-pipe


【解决方案1】:

transform 函数中的 value 参数是一个对象数组(类别)。 javascript 对象的原型中没有 indexOf 函数,所以这就是您收到此错误的原因。

假设你想要做的是过滤掉这些对象,如果它们的属性都不包含term,那么你应该这样做:

transform(value: any, term: any) {
  if (!term) return value;
  return value.filter((item: any) => {
    for (let prop in item) {
      if (typeof item[prop] === "string" && item[prop].indexOf(term) > -1) {
        return true;
      }
    }
    return false;
  });
}

【讨论】:

  • 太完美了!
猜你喜欢
  • 2017-04-18
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2017-03-25
  • 2017-06-21
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多