【问题标题】:Angular2 order JSON data by fieldAngular2按字段排序JSON数据
【发布时间】:2017-10-25 00:39:05
【问题描述】:

我目前正在通过后端从我的服务获取的 angular2 应用程序上显示 JSON 数据,html 如下所示:

<tbody *ngFor=" let user of users | sort: 'points'">
                <td> {{user.id}} </td>
                <td> {{user.name}} </td>
                <td> {{user.points}} </td>
</tbody>

我正在尝试根据 points 字段以降序显示此数据,因此将首先显示具有最高点数的用户。

这是我的排序管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
    if ( a[args] < b[args] ){
        return -1;
    }else if( a[args] > b[args] ){
        return 1;
    }else{
        return 0;   
    }
});
return array;
 }
}

我已在 app.module.ts 中导入管道并将其添加到声明中,但尝试加载数据时出错:

Cannot read property 'sort' of undefined

有谁知道我做错了什么?谢谢

【问题讨论】:

    标签: json angular pipe pipes-filters


    【解决方案1】:

    它抛出错误是因为没有值。只需检查数组是否在您的管道中有值,如下所示,

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
        name: 'sort'
    })
    export class SortPipe implements PipeTransform {
        transform(array: Array<string>, args: string): Array<string> {
            if(!array)
            {
                return [];
            }
            if (array & array.length > 0) {
                array.sort((a: any, b: any) => {
                    if (a[args] < b[args]) {
                        return -1;
                    } else if (a[args] > b[args]) {
                        return 1;
                    } else {
                        return 0;
                    }
                });
                return array;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      在尝试呈现表格之前,您应该确保您的用户已初始化。试试这个:

      <table *ngIf="users">
           <tbody *ngFor=" let user of users | sort: 'points'">
                  <td> {{user.id}} </td>
                  <td> {{user.name}} </td>
                  <td> {{user.points}} </td>
           </tbody>
      </table>
      

      否则你的管道看起来应该可以工作。

      顺便说一句,Angular documentation 建议不要在管道中排序。他们说它效率不高,如果你在组件本身中排序,你会得到更好的代码。

      【讨论】:

        猜你喜欢
        • 2017-12-21
        • 1970-01-01
        • 2016-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-30
        • 2018-08-18
        相关资源
        最近更新 更多