【问题标题】:Angular 6 Filter observable array with pipe带有管道的Angular 6过滤器可观察数组
【发布时间】:2019-06-05 07:52:05
【问题描述】:

我在 ngFor 循环中显示一个对象列表,我想用管道过滤这个列表。

我的研究让我明白了这一点:

按.pipe.ts 过滤:

import { Pipe, PipeTransform } from '@angular/core';
import { UserLink } from '../_models/user-link';

@Pipe({
    name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {
    transform(items: User[], isActive: boolean): any {
        if (!items) { return []; }
        return items.filter(x => x.isActive === isActive);
    }
}

在 my.component.html 中:

<tr *ngFor="let item of items$|async|filterBy: {isActive: false}">
    <td>{{item.firstname}}</td>
    <td>{{item.lastname}}</td>
    <td>{{item.age}}</td>
</tr>

但结果不是我所期望的:我的数组是空的。

为了让它发挥作用,我错过了什么?

我在这个 stackblitz (https://stackblitz.com/edit/angular-46atle) 中尝试了我的解决方案并且它有效。但我仍然无法让它在我的项目中工作。我检查了对象的属性和其余代码,但看不到错误在哪里

[编辑]

问题解决了!我正在过滤的对象和我认为我正在过滤的对象之间缺少投射。! 初学者的错误!

感谢您的建议!

【问题讨论】:

  • 可能是&lt;tr *ngFor="let item of items$|async|filterBy: false"&gt;
  • 我仍然有同样的问题:没有结果。我通过控制台检查了我的过滤器参数是否正确填写并且没有问题。就像过滤器不起作用或返回空数组一样。是因为我正在使用 observable 吗?也许我对管道代码中的项目做错了什么?

标签: angular observable ngfor angular-pipe


【解决方案1】:

您不应该使用管道来过滤或排序列表:

https://angular.io/guide/pipes#no-filter-pipe

Angular 团队和许多经验丰富的 Angular 开发人员都很有实力 建议将过滤和排序逻辑移动到组件中 自己。

例如,您可以将数组转换为 observable 并使用可管道的 RxJS 运算符应用您的过滤逻辑:

Rx.Observable.from(items)
    .pipe(
         filter(item => item.size >= 1),
         map(item => "Item name: " + item.name),
         // more filtering logic
      ) 
    .subscribe(item => console.log(item))
);

【讨论】:

  • 感谢您的建议。我将根据此更新我的代码。但是我仍然有一个可能有用的用例:如果您想根据两种不同的状态(例如 isActive 状态)显示一个相同的列表,那么为活动行和非活动行复制代码不是更重吗?即使在这种情况下,管道仍然很贵?
  • 我认为您不必复制任何内容,您可以从 *ngFor 循环中访问您的 isActive 布尔值,并使用它以您喜欢的任何方式操作您的模板,对吗?
  • 这可能是一个很好的解决方案,但我使用的是分页器,所以我不确定结果。但是越简单越好,重复列表应该是没有过滤管道的最佳方法。
【解决方案2】:

您不必传递对象,您的管道接受数组和布尔值作为输入。 只需尝试如下

<tr *ngFor="let item of items$|async|filterBy: false">

【讨论】:

    【解决方案3】:

    你可以像这样过滤你的数组:

     <tr *ngFor="let item of _items | filter:{label: filterText}">{{ item.label }}</li>
    

    https://long2know.com/2016/11/angular2-filter-pipes/

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 2020-06-23
      • 2018-07-01
      • 2020-09-10
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      相关资源
      最近更新 更多