-1

I am trying to create array of objects dynamically in Angular. I have this segment of code:

 data:{title:any,date:any};
  arr:any=[]
  this.service.calendarBooking().subscribe((res: any) => {
      for (let i = 0; i < res.data.length; i++) {
        // Creating object from API Response
        this.data={title:res.data[i].name,date:res.data[i].date}
        // Pushing object to array
        this.arr.push(this.data)
      }
    })

When I am printing the array, the array responses like this:

0: {title: "spss", date: "2021-01-30"}
1: {title: "spss", date: "2021-01-29"}
2: {title: "spss", date: "2021-01-28"}

But when I am trying to access the indexes(arr[0],arr[1]) the response is undefined, length of arr is zero How to solve this issue"?

sanjay
  • 1
  • 3
  • Try using `arr[0].title` or `arr[0].date` – Nicholas K Jan 25 '21 at 10:16
  • 1
    my guess is. he tries to access outside of the subscribe, but javascript ist non-blocking – enno.void Jan 25 '21 at 10:23
  • Thank you for your response. Its giving error cant read property 0 of undefined – sanjay Jan 25 '21 at 10:27
  • Most probably you're trying outside the subscription. In that case, you can only access them inside the subscription. The data is assigned asynchronously. Please read [this](https://stackoverflow.com/a/14220323/6513921) answer in it's entirety to understand how async data works. – ruth Jan 25 '21 at 10:31

3 Answers3

0

this.arr is different and the arr you have written below data:{title:any,date:any}; is different,

either push it to arr.push(this.data) or access like (this.arr[0] , this.arr[1])

Prashant Singh
  • 611
  • 1
  • 5
  • 14
0

First, print array after for loop if you get expected result then the problem is with callbacks so do async wait call that will await the system until receive response or error.

and if it didn't print data after for loop then type the array variable. THis is how you can type it. arr: Array = [{}];

0

check like the following

this.service.calendarBooking().subscribe((res: any) => {
     for (let i = 0; i < res.data.length; i++) {
         //this.data={title:res.data[i].name,date:res.data[i].date}
         // Pushing object to array
         this.arr.push({
              title: res.data[i].name,
              date:res.data[i].date
         });
     }
     console.log(this.arr,this.arr[1]);
});

I think this will help you

Msk Satheesh
  • 1,398
  • 1
  • 6
  • 7