Angular2排序数组,用于在html中显示*ngFor

Fre*_*red 8 typescript angular

我正在浏览所有帖子

<li *ngFor="let post of posts">
Run Code Online (Sandbox Code Playgroud)

当我显示每个帖子的日期时:

{{post.date | date:'yyyy-MM-dd HH:mm:ss'}}
Run Code Online (Sandbox Code Playgroud)

我想要做的是按照最新的顺序显示所有帖子.

我尝试过使用如下管道:

<li *ngFor="let post of posts | order-by-pipe">
Run Code Online (Sandbox Code Playgroud)
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;
  }

}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我收到错误:

TypeError: Cannot read property 'toUpperCase' of undefined ("
[ERROR ->]*ngFor="let post of posts | order-by-pipe">
Run Code Online (Sandbox Code Playgroud)

欢迎任何帮助,谢谢

sil*_*sod 11

当你order-by-pipe用作选择器时,它试图找到变量order by,pipe并且知道谁知道变量.

更改name:管道以orderByPipe解决问题.

那很奇怪.

这是一个相同代码的演示,不同的名称:http://plnkr.co/edit/BXkrPqeMYuJMhkx94i6M?p = preview


Mic*_*gal 9

Angular团队建议不要在Angular 2中使用管道进行排序,并故意从AngularJS中删除此功能.详见https://angular.io/guide/pipes:

Angular不提供这样的管道,因为它们表现不佳并且防止侵略性缩小......过滤和特别是分类是昂贵的操作.当Angular每秒多次调用这些管道方法时,即使是中等大小的列表,用户体验也会严重降低.过滤器和orderBy经常在AngularJS应用程序中被滥用,导致抱怨Angular本身很慢...... Angular团队和许多经验丰富的Angular开发人员强烈建议将过滤和排序逻辑移入组件本身.

请参阅/sf/answers/3016466631/上的类似讨论