Home > other >  Angular OnInit for loop push returns an emtpy array
Angular OnInit for loop push returns an emtpy array

Time:09-29

To being with, in ngOnInit I create fill up the items array:

id: string = '';
items: Item[] = [];

ngOnInit(): void {
    this.id = this.activatedRoute.snapshot.params['id'];
    this.itemService.getItems(this.id).subscribe({
      next: (res) => this.items = res
    })

So far so good, I get the items array. Now by using *ngFor = "let item of items" I can print out a list of {{item.color}} in the HTML page. That means I have the items array filled up.

Next, I want to push each item.color into a separate array. So in the same ngOnInit method I continue like this:

let colorArray:string[] = [];
    for (let item of this.items) {
      colorArray.push(item.color)
    }

And in the same ngOnInit method I console log it:

console.log(colorArray);

However, it returned an empty array. What went wrong?

CodePudding user response:

it would be a timing issue - the array is trying to be filled before the data is available.

I would refactor to map a new array on the return of the results - that way its always going to be filled when the results are returned.

id: string = '';
items: Item[] = [];
colorArray:string[] = [];

ngOnInit(): void {
    this.id = this.activatedRoute.snapshot.params['id'];
    this.itemService.getItems(this.id).subscribe({
      next: (res) => {
        this.items = res;
        this.colorArray = res.map(r => r.color);
      }
   })
}

CodePudding user response:

setTimeout(()=>{
    let colorArray:string[] = [];
    for (let item of this.items) {
      colorArray.push(item.color)
    }
},1000)

This is a timing issue something related to the difference between the queue and the stack, also the second function is synchronous, which mean it return the result before the first one which have to wait for back-end response to subscribe and then return value. Also you can take advantages of angular lifecycle hooks and but the second one inside ngAfterViewInit or ngDoCheck

  • Related