Angular 2 - Sort list from Observable

Thibs picture Thibs · Dec 19, 2016 · Viewed 21.8k times · Source

What is the best way to sort a list of items coming from an Observable and still be able to use the async pipe? (I read that making a custom sort pipe is not really efficient.) I want to avoid subscribing and keeping a local copy of data and thus just using async pipe...

//can I use map here and filter items right in the observable and get rid of subscribe?

this.test$ = Observable.of(['one', 'two', 'three'])
    .subscribe((data) => {
        data.sort((a, b) => {
            return a < b ? -1 : 1;
         });
        this.data = data;
     });

template:

<div *ngFor='let item of data'>
<!-- want to be able to use async pipe here -->

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Dec 19, 2016

If you call .subscribe() you get a Subscription, the async pipe expects an Observable.

If you change it to

this.test$ = Observable.of(['one', 'two', 'three'])
.map((data) => {
    data.sort((a, b) => {
        return a < b ? -1 : 1;
     });
    return data;
 });

you can use the async pipe with test$