【问题标题】:Angular2 sorting array for displaying in *ngFor in html用于在 html 中显示 *ngFor 的 Angular2 排序数组
【发布时间】:2017-07-21 04:56:45
【问题描述】:

我正在循环浏览所有帖子

<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">

欢迎任何帮助,谢谢

【问题讨论】:

  • 这似乎具有误导性,toUpperCase 的调用地址在哪里?不在您发布的任何地方。
  • 我知道,该错误并没有提供太多帮助,这就是为什么我认为可能是管道导致它的原因。没有管道,我就不会出错。

标签: angular typescript


【解决方案1】:

当您使用 order-by-pipe 作为选择器时,它会尝试查找变量 order bypipe 并且谁知道它们会发生什么。

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

这很奇怪。

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

【讨论】:

    【解决方案2】:

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

    Angular 不提供这样的管道,因为它们的性能很差,而且 防止激进的缩小...过滤,尤其是排序 是昂贵的操作。用户体验可能会严重下降 当 Angular 多次调用这些管道方法时,甚至是中等大小的列表 每秒次。 filter 和 orderBy 经常被滥用 AngularJS 应用程序,导致抱怨 Angular 本身很慢...... Angular 团队和许多经验丰富的 Angular 开发人员强烈 建议将过滤和排序逻辑移动到组件中 自己。

    https://stackoverflow.com/a/43092380/3211269查看类似的讨论

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2019-09-03
      • 2017-09-13
      • 2018-07-02
      • 1970-01-01
      • 2017-07-31
      相关资源
      最近更新 更多