TypeError: Cannot read property 'sort' of undefined at SortPipe.transform ,Why?
我创建了一个管道来对数组进行排序,但是当我使用管道进行排序时,它显示错误:
Error: Uncaught (in promise): TypeError: Cannot read property 'sort' of undefined.
管道.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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; } } |
我已将
管道.html
1 2 3 4 5 6 7 8 | <ion-item item-detail *ngFor="let exhibit of exhibits | sortBy : 'name' let i = index" name="exhibit"> {{ exhibit?.name }} <h5>{{ exhibit.plan }}</h5> <h5>{{ exhibit.link }}</h5> <h5>{{ exhibit.stall }}</h5> <h5>{{ exhibit.description }}</h5> </ion-item> |
尝试将管道代码package在 if 语句中,该语句检查以确定数组是否未定义,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } |