简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM