我正在尝试在Angular 2中创建一个自定义管道,它将对一组对象进行排序.我从这篇文章中获得了一些帮助.但是,我似乎无法让这个工作.
我的烟斗看起来像这样:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
管道的使用如下所示:
<div *ngFor="#c of countries | orderByAsync">{{c.name}}</div>
Run Code Online (Sandbox Code Playgroud)
就像视图永远不会被通知承诺已经解决并且数据已被返回.
我错过了什么?
Dou*_*las 13
内置async管道在promise解析时注入ChangeDetectorRef并调用markForCheck()它.要在一个管道中完成所有操作,您应该遵循该示例.您可以在此处查看Typescript源代码.
但是,我建议忘记自己处理异步,而是写一个纯无状态排序管道并用内置async管道链接它.为此,您可以编写管道来处理裸露Array,而不是承诺,并像这样使用它:
<div *ngFor="#c of countries | async | orderBy">{{c.name}}</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9778 次 |
| 最近记录: |