[英]How can I use filter operator of rxjs?
我有一些代碼,我可以觀察到。 我想將數組過濾方法更改為過濾 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 的過濾器運算符與 JavaScript 的原生Array.filter()方法完全不同。
RxJS 的過濾器操作符允許你
通過僅發出滿足指定謂詞的項來過濾源 Observable 發出的項。
換句話說,RxJS filter
算子從 stream 中排除了滿足一定條件的 observable,這與Array.filter()
所做的完全不同,后者是根據特定條件從數組中過濾/刪除對象或值。
例如,下面的序列使用 RxJS filter()
運算符過濾掉長度小於 1 的tags
。
this.articleTags
.pipe(
filter(tags => tags.length > 1),
).subscribe(res => {
console.log(res);
// do the rest
})
因此,當返回可觀察值時,生成的 output 將是長度大於 1 的articleTags
。
因此,我認為您不應該使用 RxJS filter
運算符來替換map()
運算符中的過濾操作。
據我所知,如果滿足此條件,您想過濾標簽this.selectedArticleTags = this.article.tagIds ,然后按此條件過濾數組tags.filter(tag => this.article.tagIds.includes(tag .id)) .
代碼應如下所示:
@Input() public articleTags: Observable<ALArticleTag[]>;
public selectedArticleTags: ALArticleTag[] = [];
public ngAfterViewInit(): void {
this.articleTags.pipe(
take(1),
filter(tags => this.selectedArticleTags = this.article.tagIds),
map(tags => tags.filter(tag => this.article.tagIds.includes(tag.id));
}),
).subscribe(response => {
this.selectedArticleTags = response;
this.changeDetection.markForCheck();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.