0

I am calling api to get data on ngOnInit. However I am not able to assign the data class variable. Below is the related code

  tasks: Task[];

  ngOnInit() {

    this.apiService.getTasks()
      .subscribe( data => {
        Object.keys(data).map((index) => {
          this.tasks.push(data[index]);
       });
      });

  }

I get error saying 'TypeError: Cannot read property 'push' of undefined' for statement

this.tasks.push(data[index]);

But the tasks is already defined as array.

Can anyone help me here, the scope really confuses me

2
  • 3
    You should declare an empty array tasks: Task[] = [] Commented May 29, 2020 at 9:35
  • Thank you @SameerKhan, How could I not see that, Thanks for pointing out Commented May 29, 2020 at 9:42

2 Answers 2

1

If all you do in the map is to return the value of the property, you could use Object.values().

this.apiService.getTasks().subscribe(data => {
  this.tasks = Object.values(data);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Map will return a new array so no need of pushing inside map. Hence Your code should be

this.apiService.getTasks()
      .subscribe( data => {
        this.tasks = Object.keys(data).map((index) => {
         return data[index];
         });
      });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.