Jeremy Thomas
Jeremy Thomas

Reputation: 6674

How to use rxjs filter with Angular 2's async pipe

I have a Observable that I am trying to filter but I cannot seem to get it to display properly in my view.

comments = new Rx.BehaviorSubject([
    {body: 'foo', commentable_type: 'Client'},
    {body: 'foo', commentable_type: 'Client'},
    {body: 'foo', commentable_type: 'Purchase'},
    {body: 'foo', commentable_type: 'Client'},
    {body: 'foo', commentable_type: 'Payment'},
]);

comments$ = comments.asObservable();

clientCommentStream$ = this.comments$.filter(comment => comment['commentable_type'] === 'Client');

and in my view, this works perfectly:

<li *ngFor="let comment of comments$ | async">
    {{ comment.body }}, {{ comment.commentable_type }}
</li>

but this displays nothing:

<li *ngFor="let comment of clientCommentStream$ | async">
    {{ comment.body }}, {{ comment.commentable_type }}
</li>

My stack blitz shows that the filtering is working, but it won't display because it seems the structure of the object has changed. Any insight would be helpful.

Upvotes: 1

Views: 809

Answers (1)

Vamsi
Vamsi

Reputation: 9780

you are missing return statement

clientCommentStream$ = this.comments$.filter(function(comment) {
    return comment.commentable_type == 'Client'; <-- missing "return"
})

OR use arrow function

clientCommentStream$ = this.comments$
                       .filter(comment => comment.commentable_type == 'Client')

EDIT: used Rx.Observable.from instead of Rx.BehaviorSubject

from docs BehaviorSubject emits most recent item, not sure how it works

Upvotes: 2

Related Questions