Reputation: 315
I have some code, where I have observable. I want to change array filter method to filter of rxjs. How can I use filter operator of 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();
});
}
Upvotes: 2
Views: 5504
Reputation: 547
From what I see, you want to filter tags by if this condition is satisfied this.selectedArticleTags = this.article.tagIds and then you filter the array by this condition tags.filter(tag => this.article.tagIds.includes(tag.id)).
The code should look like this:
@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();
});
}
Upvotes: 0
Reputation: 42526
Do take note that RxJS's filter operator is quite different from JavaScript's native Array.filter() method.
RxJS's filter operator allows you to
Filter items emitted by the source Observable by only emitting those that satisfy a specified predicate.
In other words, the RxJS filter
operator excludes observable from the stream that meets a certain condition, which is quite different from what Array.filter()
does, which is to filter/remove objects or values from the array based on a certain condition.
For instance, the below sequence uses the RxJS filter()
operator to filter out tags
whose length are less than 1.
this.articleTags
.pipe(
filter(tags => tags.length > 1),
).subscribe(res => {
console.log(res);
// do the rest
})
Therefore, the resulting output when the observable values have been returned would be articleTags
whose length is more than 1.
Hence, I don't think you should use the RxJS filter
operator to replace the filtering operation within the map()
operator.
Upvotes: 3