我试图对我使用http.get从服务返回的可观察对象进行排序。订阅后,我曾尝试对服务中的数据以及组件中的数据进行排序。但是我总是得到错误排序不是一个函数。我是Angular的新手,但我一直坚持这样做。感谢您的帮助。谢谢
JSON sample
"data": [
{
"codeValue": 2,
"codeType": 145,
"description": "ASSIMILATION"
},
{
"codeValue": 3,
"codeType": 145,
"description": "BANKRUPTCY"
},
{
"codeValue": 4,
"codeType": 145,
"description": "BID TENDER"
},
event.interface.ts
export interface IEventInterface {
codeValue: number;
codeType: number;
description: string;
}
Service.ts
getEventType():
{
return this.http.get<IEventInterface[]>('/gpscaservices/v1/system-
descriptions?codeType=145&codeValue=');
}
Create.Component.ts
orderedEvent: any;
eventTypes: any;
this._dataService.getEventType().subscribe({
next: (response: IEventInterface[]) => {
this.eventTypes = response ;
this.sortBy('description');
}
sortBy(field: string ) {
this.eventTypes.sort((a: any, b: any) =>{
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
this.orderedEvent = this.eventTypes;
Create.Component.html
nx-option *ngFor="let eventType of orderedEvent.data"
[value]="eventType.codeValue">
{{ eventType.description }}
/nx-option>
答案 0 :(得分:0)
我认为您错过了data
字段。
sortBy(field: string ){
this.eventTypes.data.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
this.orderedEvent = this.eventTypes;
}
最好定义一个明确的类型,而不要使用任何类型。
export interface EventData {
data: IEventInterface[]
}
orderedEvent: EventData;
eventTypes: EventData;
答案 1 :(得分:-1)
您可以像这样设置排序功能
sortEventTypes(sortString : string){
this.eventTypes.sort(function (a, b) {
return a[sortString] - b[sortString];
});
}