关于angular:用于在ngFor中显示的Angular2排序数组

Angular2 sorting array for displaying in *ngFor in html

我正在浏览所有帖子

1
<li *ngFor="let post of posts">

在显示每个帖子的日期时,我会做:

1
{{post.date | date:'yyyy-MM-dd HH:mm:ss'}}

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

我尝试使用类似以下的管道:

1
<li *ngFor="let post of posts | order-by-pipe">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
  }

}

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

1
2
TypeError: Cannot read property 'toUpperCase' of undefined ("
[ERROR ->]*ngFor="let post of posts | order-by-pipe">

任何帮助都将受到欢迎,谢谢


当使用order-by-pipe作为选择器时,它会尝试查找变量orderbypipe,并由谁知道它们的含义。

将管道中的name:更改为orderByPipe可解决此问题。

那太奇怪了。

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


Angular团队建议不要在Angular 2中使用管道进行排序,并有意从AngularJS中删除了此功能。如https://angular.io/guide/pipes上所述:

Angular doesn't offer such pipes because they perform poorly and
prevent aggressive minification... Filtering and especially sorting
are expensive operations. The user experience can degrade severely for
even moderate-sized lists when Angular calls these pipe methods many
times per second. filter and orderBy have often been abused in
AngularJS apps, leading to complaints that Angular itself is slow...
The Angular team and many experienced Angular developers strongly
recommend moving filtering and sorting logic into the component
itself.

在https://stackoverflow.com/a/43092380/3211269

上查看类似的讨论