25

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 -->
Thibs
  • 8,058
  • 13
  • 54
  • 85

1 Answers1

30

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$

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Thanks Günter for confirming that I can use the Observable's map operator to sort, appreciate it. – Thibs Dec 19 '16 at 14:37