Angular 2 - 来自Observable的排序列表

Thi*_*ibs 17 rxjs5 angular

什么是sort一个项目列表的最佳方式来自一个Observable仍然能够使用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;
     });
Run Code Online (Sandbox Code Playgroud)

模板:

<div *ngFor='let item of data'>
<!-- want to be able to use async pipe here -->
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 26

如果你打电话给.subscribe()Subscription,那么异步管道需要一个Observable.

如果你改成它

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

你可以使用异步管道 test$

  • 感谢 Günter 确认我可以使用 Observable 的 map 运算符进行排序,谢谢。 (2认同)