2017-07-19 117 views
4

我已创建了一个管道数组排序,但是当我使用管道排序它说错误:TypeError:无法在SortPipe.transform中读取未定义的属性'sort',为什么?

Error: Uncaught (in promise): TypeError: Cannot read property 'sort' of undefined.

pipe.ts

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

@Pipe({name: "sortBy"}) 
export class SortPipe { 
    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; 
    } 
} 

我已经包含在声明中SortPipe和@NgModule的提供者。

pipe.html

<ion-item item-detail *ngFor="let exhibit of exhibits | sortBy : 'name' 
     let i = index" name="exhibit"> 
    <h2>{{ exhibit?.name }}</h2> 
    <h5>{{ exhibit.plan }}</h5> 
    <h5>{{ exhibit.link }}</h5> 
    <h5>{{ exhibit.stall }}</h5> 
    <h5>{{ exhibit.description }}</h5> 
</ion-item> 

回答

5

尝试在检查以确定是否数组是不确定的,像这样的if语句包裹的管道代码:

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

    @Pipe({ name: "sortBy" }) 

    export class SortPipe { 

    transform(array: Array<string>, args: string): Array<string> { 
     if (array !== undefined) { 
      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; 
    } 
相关问题