Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Sort list from Observable

Tags:

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 --> 
like image 851
Thibs Avatar asked Dec 19 '16 14:12

Thibs


1 Answers

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$

like image 101
Günter Zöchbauer Avatar answered Nov 11 '22 01:11

Günter Zöchbauer