我使用角度6,并希望在UI呈现结果之前过滤异步管道的结果。
这是我的代码
this.results = this.form.get('name').valueChanges.pipe(
filter(formdata => formdata.name.length > 0),
switchMap( formdata => this.service.getNames(formdata.name))
);
和模板
<div *ngIf='results | async ; let items'>
<div *ngFor='let item of items'>{{item.id}} {{item.name}} </div>
</div>
从管道中,我得到一些ID和名称。我已经有一组ID。我想过滤管道的ID,而不渲染那些已经在数组中的ID。
所以,这就是我要做的。
array = [{id:1,name:'one'},{id:2,name:'two'}];//I already have this
管道中新版本的过滤器
this.results = this.form.get('name').valueChanges.pipe(
filter(formdata => formdata.name.length > 0),
switchMap( formdata => this.service.getNames(formdata.name)) ,
filter(checkIfResultIdInArray())//pseudocode
);
假设checkIfResultIdInArray
是我创建的函数。过滤并返回array
以外的所有ID。因此,以模板结尾的ID /名称不是{id:1,name:'one'},{id:2,name:'two'}
。
或者也许我可以以某种方式过滤模板?
答案 0 :(得分:2)
@Davy的答案是我自己做的。但是,另一个选择是使用管道。如果您想重复使用此功能,这就是方法。
@Pipe({name:'filterOnId'})
export class FilterOnIdPipe implements PipeTransform {
transform(list : MyObject[], acceptedIds : number[]){
return list.filter(item => acceptedIds.indexOf(item.id) > -1);
}
}
和模板中
<div *ngFor='let item of results | async | filterOnId : acceptedIds'>
{{item.id}} {{item.name}}
</div>
答案 1 :(得分:1)
如评论中所建议,您可以将AsyncPipe
替换为常规数组,或更改发射值的值(@Davy的解决方案很好)。
但是,有一个基于模板的解决方案。对于那些不想将组件的逻辑与视图显示合并的人来说,我把它放在这里。
组件
result$ = of([1,2,3,4,5,6,7,8]); // for the sake of example
isAcceptedThing(thing){
return thing%2 != 0 // accept only odd numbers
}
模板
<ul >
<ng-container *ngFor="let thing of result$ | async">
<li *ngIf="isAcceptedThing(thing)">
filtered thing = {{ thing }}
</li>
</ng-container>
</ul>
输出
- 已过滤的事物= 1
- 已过滤的事物= 3
- 已过滤的事物= 5
- 已过滤的事物= 7
答案 2 :(得分:1)
我想这就是您想要做的:
this.results = this.form.get('name').valueChanges.pipe(
filter(formdata => formdata.name.length > 0),
switchMap( formdata => this.service.getNames(formdata.name)) ,
map(names => names.filter(n => checkIfResultIdInArray(n)))
);
通常,在这样的设置中,我还将添加一个debounceTime运算符以防止请求过多。