Angular 2 - Sort list from Observable

风格不统一 提交于 2019-12-03 15:35:28

问题


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 -->

回答1:


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$



来源:https://stackoverflow.com/questions/41224749/angular-2-sort-list-from-observable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!