typescript 按值过滤的对象的angular2 typescript数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43337893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:26:21  来源:igfitidea点击:

angular2 typescript array of object filter by value

jsonangulartypescript

提问by stackUser44

I have an array getting data from JSON file. I am able to store an array of objects into my Task[]. Now I want to retrieve the data by status ('Submitted' or 'Resolved' etc). I tried many ways, but unable to achieve it. Please help me.

我有一个从 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

任务.ts

export interface Task {
  taskId: any;
  taskname: any;
  status: any;
}

taskService.ts

任务服务.ts

getTask() {
  return this.http.get('../app/common/task.json')
    .toPromise()
    .then(res => < Task[] > res.json().data)
    .then(data => {
      return data;
    });

}

taskCompnent.ts

任务组件.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 is what I tried to filter by status:

这是我尝试按状态过滤的内容:

 this.sortedList = this.taskList.filter(
      task => task.status ==='Submitted');

showing error below error:

在错误下方显示错误:

Cannot read property 'filter' of undefined

无法读取未定义的属性“过滤器”

回答by Sajeetharan

It's because promises / HTTP requests are asynchronous. You need to add filter within the callback of the promises, if you place it outside taskList will be undefined so the filter cannot be applied

这是因为 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');

    });