我有一些代码,我可以观察到。我想将数组过滤方法更改为 rxjs 的过滤器。如何使用rxjs的过滤运算符?
@Input() public articleTags: Observable<ALArticleTag[]>;
public selectedArticleTags: ALArticleTag[] = [];
public ngAfterViewInit(): void {
this.articleTags.pipe(
take(1),
map(tags => {
return this.selectedArticleTags = this.article.tagIds ? tags.filter(tag => {
return this.article.tagIds.includes(tag.id);
}) : [];
}),
).subscribe(response => {
this.selectedArticleTags = response;
this.changeDetection.markForCheck();
});
}
最佳答案
请注意 RxJS 的 filter运算符与 JavaScript 原生的 Array.filter() 有很大不同方法。
RxJS 的过滤运算符允许您
Filter items emitted by the source Observable by only emitting those that satisfy a specified predicate.
换句话来说,RxJS filter
运算符从流中排除满足特定条件的 observable,这与 Array.filter()
的做法有很大不同,后者是根据特定条件从数组中过滤/删除对象或值。
例如,下面的序列使用 RxJS filter()
运算符过滤掉长度小于 1 的 tag
。
this.articleTags
.pipe(
filter(tags => tags.length > 1),
).subscribe(res => {
console.log(res);
// do the rest
})
因此,返回可观察值时的结果输出将是长度大于 1 的 articleTags
。
因此,我认为您不应该使用 RxJS filter
运算符来替换 map()
运算符中的过滤操作。
关于angular - 如何使用rxjs的过滤器运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58611177/