1

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.

10
  • On stackblitz.com it would be easy to create a full Angular reproduction. Commented Feb 2, 2018 at 11:43
  • I made it. Still can't figure it out stackblitz.com/edit/angular-ld5aeu Commented Feb 2, 2018 at 12:02
  • The correct link is stackblitz.com/edit/angular-ld5aeu Commented Feb 2, 2018 at 12:03
  • my apologies, new to stack blitz Commented Feb 2, 2018 at 12:06
  • 1
    If you pass an array, you need to remove all items from the array that don't match your criteria. If you pass the items individually, you need to collect them to an array afterwards because *ngFor expects an array, not a sequence of individual items. scan should do that as far as I remember. Commented Feb 2, 2018 at 12:22

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I edited my question because while this was incorrect it was not the casue of my error
jsfiddle.net/g5pj065m/210 tried using Observable.from instead of BehaviorSubject
I guess having the iterator makes a difference here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.