Angular 2-Observable的排序列表 [英] Angular 2 - Sort list from Observable

查看:83
本文介绍了Angular 2-Observable的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sort来自Observable的项目列表并且仍然能够使用async pipe的最佳方法是什么? (我读过,创建自定义排序管道并不是真正有效.)我想避免订阅和保留数据的本地副本,因此仅使用异步管道...

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;
     });

模板:

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

推荐答案

如果调用.subscribe(),您将得到一个Subscription,则异步管道需要一个Observable.

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

如果将其更改为

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

您可以将异步管道与test$

这篇关于Angular 2-Observable的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆