Dam*_*ams 0 observable ngfor angular-pipe angular
我在 ngFor 循环中显示一个对象列表,我想用管道过滤这个列表。
我的研究使我想到了这一点:
filter-by.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);
}
}
Run Code Online (Sandbox Code Playgroud)
在 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>
Run Code Online (Sandbox Code Playgroud)
但结果不是我所期望的:我的数组是空的。
我想念什么才能让它发挥作用?
我在这个 stackblitz ( https://stackblitz.com/edit/angular-46atle ) 中尝试了我的解决方案并且它有效。但我仍然无法让它在我的项目中工作。我检查了对象的属性和代码的其余部分,但看不到我的错误在哪里
[编辑]
问题解决了!我正在过滤的对象和我认为我正在过滤的对象之间缺少一个演员表。!初学者的错误!
感谢您的建议!
你不应该使用管道来过滤或排序列表:
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))
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7908 次 |
| 最近记录: |