我有一个数组从JSON文件中获取数据。我能够将一组对象存储到我的Task[]
中。现在我想按状态检索数据('已提交'或'已解决'等)。我尝试了很多方法,但无法实现。请帮帮我。
data: [{
taskname: 'Test1',
taskId: '1',
status: 'Submitted'
}, {
taskname: 'Test2',
taskId: '2',
status: 'Resolved'
}, {
taskname: 'Test3',
taskId: '4',
status: 'Submitted'
}, {
taskname: 'Test4',
taskId: '5',
status: 'In Progress'
}, {
taskname: 'Test5',
taskId: '6',
status: 'Resolved'
}, {
taskname: 'Test6',
taskId: '7',
status: 'Submitted'
}
}]
Task.ts
export interface Task {
taskId: any;
taskname: any;
status: any;
}
taskService.ts
getTask() {
return this.http.get('../app/common/task.json')
.toPromise()
.then(res => < Task[] > res.json().data)
.then(data => {
return data;
});
}
taskCompnent.ts
export class TaskComponent implements OnInit {
taskList: Task[];
datasource: Task[];
sortedList: Task[];
ngOnInit() {
this.taskService.getTask().then(files => this.files = files);
this.vecService.getData().then(taskList => {
this.datasource = taskList;
this.taskList = this.datasource; // Storing data into my task list array
});
}
}
这是我尝试按状态过滤的内容:
this.sortedList = this.taskList.filter(
task => task.status ==='Submitted');
显示错误低于错误:
无法读取未定义的属性“过滤器”
答案 0 :(得分:5)
这是因为promises / HTTP请求是异步的。你需要在promises的回调中添加过滤器,如果你将它放在taskList之外将是未定义的,因此无法应用过滤器
this.vecService.getData().then(taskList => {
this.datasource = taskList;
this.taskList = this.datasource;// Storing data into my task list array
this.sortedList = this.taskList.filter(
task => task.status ==='Submitted');
});