我正在浏览所有帖子
<li *ngFor="let post of posts">
当我显示每个帖子的日期时:
{{post.date | date:'yyyy-MM-dd HH:mm:ss'}}
我想要做的是按照最新的顺序显示所有帖子。
我尝试使用像:
这样的管道<li *ngFor="let post of posts | order-by-pipe">
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'order-by-pipe'
})
export class OrderByPipe implements PipeTransform{
transform(array: Array<string>, args: string): Array<string> {
if(!array || array === undefined || array.length === 0) return null;
array.sort((a: any, b: any) => {
if (a.date < b.date) {
return -1;
} else if (a.date > b.date) {
return 1;
} else {
return 0;
}
});
return array;
}
}
但它不起作用。我收到错误:
TypeError: Cannot read property 'toUpperCase' of undefined ("
[ERROR ->]*ngFor="let post of posts | order-by-pipe">
欢迎任何帮助,谢谢
答案 0 :(得分:10)
当您使用order-by-pipe
作为选择器时,它会尝试查找变量order
by
和pipe
,并知道谁知道这些变量。
将管道中的name:
更改为orderByPipe
可以解决问题。
这很奇怪。
以下是相同代码的演示,名称不同:http://plnkr.co/edit/BXkrPqeMYuJMhkx94i6M?p=preview
答案 1 :(得分:9)
Angular团队建议不要在Angular 2中使用管道进行排序,并故意从AngularJS中删除此功能。详见https://angular.io/guide/pipes:
上查看类似的讨论Angular不提供这样的管道,因为它们的性能很差 防止侵略性缩小...过滤,尤其是排序 是昂贵的操作。用户体验会严重降低 当Angular调用这些管道方法时,甚至是中等大小的列表 每秒一次。过滤器和订单经常被滥用 AngularJS应用程序,导致抱怨Angular本身很慢...... Angular团队和许多经验丰富的Angular开发人员 建议将过滤和排序逻辑移动到组件中 本身。