【问题标题】:Angular custom pipes returns error with table data角度自定义管道返回表数据错误
【发布时间】:2019-02-25 00:52:55
【问题描述】:

component.html:

<input 
  type="text" 
  [(ngModel)]="searchText" 
  placeholder="search your products here" 
  name="searchText">

<table class="table table-bordered">
  <thead>
    <tr>
      <th>Id</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let obj of product| filter: searchText">
      <td>{{obj.id}}</td>
      <td>{{obj.description}}</td>
    </tr>
  </tbody>
</table>

过滤器.ts:

transform(items: any, searchText: string): any[] {
  if (!items || !searchText || searchText === undefined) {
    return items;
  }

  return items.filter(items =>
    items.description.toLowerCase().includes(searchText.toLowerCase));
}

控制台显示项目。描述未定义。

model.ts:

export class products{
  id: number;
  description: string;    
}

在页面加载之前没有错误,一旦我开始在搜索框中输入,就会显示错误。错误显示在下面的代码中。

<input 
  type="text" 
  [(ngModel)]="searchText" 
  placeholder="search your issues here" 
  name="searchText">

【问题讨论】:

  • 什么是product?它是如何定义的?
  • 它存储了getProducts()的响应
  • 您的回复可能不会为某些项目返回 description 字段。我建议您在将响应分配给product 的行处放置一个断点来检查这一点。
  • 在管道的transform 方法中添加断点以查看items 参数的内容也是一个好主意。
  • 我得到对象类型的数据

标签: angular angular-filters angular2-custom-pipes


【解决方案1】:

你不是在这里打电话给searchText.toLowerCase。你需要调用它。此外,您将输入和每个项目命名为items。这可能是另一个问题。

将您的 transform 实现更改为:

transform(items: any, searchText: string): any[] {
  if (!items || !searchText || searchText === undefined) {
    return items;
  }

  return items.filter(item =>
    item.description.toLowerCase().includes(searchText.toLowerCase()));
}

当然,除非这是您的 OP 中的拼写错误。

这里有一个Sample StackBlitz 供您参考。

【讨论】:

  • 现在错误消失了,但我搜索时没有显示结果
  • 修复它..实际上我之前调用了 toLowerCase 而不是 toLowerCase()。
  • 感谢您的专业知识 Sidd..!继续帮助我们。非常感谢您
猜你喜欢
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 2020-07-29
  • 2017-08-20
  • 1970-01-01
  • 2019-11-09
  • 2019-02-11
  • 2017-12-04
相关资源
最近更新 更多