stackUser44
stackUser44

Reputation: 409

angular2 typescript array of object filter by value

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.

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 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

Upvotes: 3

Views: 11880

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222552

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

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');

    });

Upvotes: 6

Related Questions