我正在循环浏览所有帖子
<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">
欢迎任何帮助,谢谢
当您使用order-by-pipe
作为选择器时,它正在尝试找到变量order
by
和pipe
,并做谁知道对它们知道什么。
将管道中的name:
更改为orderByPipe
解决问题。
那很奇怪。
这是相同代码的演示,不同的名称:http://plnkr.co/edit/bxkrpqemyujmhkx94i6m?p = preview
Angular团队建议不要使用管道在Angular 2中进行分类,并有意从AngularJS中删除此功能。如https://angular.io/guide/pipes:
Angular不提供这样的管道,因为它们的性能不佳,并且 防止侵略性的降级...过滤,尤其是分类 是昂贵的操作。用户体验可能会严重降解 当角调用这些管道方法时,甚至中等大小的列表很多 每秒时间。过滤和订单经常被滥用 Angularjs应用程序,导致抱怨Angular本身很慢... Angular团队和许多经验丰富的角度开发人员强烈 建议将过滤和分类逻辑到组件中 本身。
请参阅https://stackoverflow.com/a/43092380/3211269