Aji*_*ith 5 sorting pipe angular
我已经创建了一个管道来对数组进行排序,但是当我使用管道对它进行排序时说错误:
错误:未捕获(在承诺中):TypeError:无法读取未定义的属性'sort'.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经包含了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>
Run Code Online (Sandbox Code Playgroud)
尝试将管道代码包装在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6137 次 |
| 最近记录: |