在Angular 2中实现异步排序管道 [英] Implementing an asynchronous sorting pipe in Angular 2

查看:193
本文介绍了在Angular 2中实现异步排序管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 2中创建一个自定义Pipe,它将对对象数组进行排序.我从这篇文章中获得了一些帮助.但是,我似乎无法正常工作.

I'm trying to create a custom Pipe in Angular 2 that will sort an array of objects. I garnered a bit of help from this post. However, I can't seem to get this working.

我的烟斗看起来像这样:

My pipe looks like this:

@Pipe({
  name: "orderByAsync",
  pure: false
})
export class AsyncArrayOrderByPipe  {
  private _promise : Promise<Array<Object>>;
  private _output: Array<Object>;
 
  transform(promise: Promise<Array<Object>>, args: any): Array<Object>{
    var _property : string = "";
    var _descending : boolean = false;

    this._property = args[0]["property"] || "";
    this._descending = args[0]["descending"] || false;

    if(!this._promise) {
      this._promise = promise.then((result) => {
        result.sort((a: any, b: any) => {
          if (a[this._property] < b[this._property])  return (this._descending ? 1: -1);
          else if (a[this._property] > b[this._property]) return (this._descending ? -1: 1);
          else return 0;
        });
    
        this._output = result;
      });
    }

    return this._output;
  }
}

管道的用法如下:

<div *ngFor="#c of countries | orderByAsync">{{c.name}}</div>

这就像视图从没有通知过诺言已经解决并且数据已经返回一样.

It's like the view is never notified that the promise has resolved and data has been returned.

我想念什么?

推荐答案

内置的async管道会注入ChangeDetectorRef,并在承诺解决时对其调用markForCheck().要在一个管道中完成所有操作,您应该遵循该示例.您可以在此处查看打字稿源.

The built in async pipe injects a ChangeDetectorRef and calls markForCheck() on it when the promise resolves. To do it all in one pipe, you should follow that example. You can view the Typescript source for that here.

但是,我建议您不要自己处理异步,而是编写一个纯的无状态排序管道,并将其与内置的async管道进行链接.为此,您将编写管道以处理裸露的Array而不是诺言,并像这样使用它:

I would suggest, however, forgetting about handling async on your own and instead write a pure stateless sorting pipe and chain it with the built in async pipe. For that, you would write your pipe to handle a bare Array, not a promise, and use it like this:

<div *ngFor="#c of countries | async | orderBy">{{c.name}}</div>

这篇关于在Angular 2中实现异步排序管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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