Issue
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?
Solution
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);
}
})
}
Answered By - gavgrif
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.