Within my angular 6 project, I am dealing with a product_id
array,
product_id: any = ["123", "456"];
ngOnInit :
ngOnInit() {
this.product_id.forEach(element => {
this.httpClient.get('https://api.myjson.com/bins/hiolc').subscribe(res => {
this.productList = [];
res.products.forEach( item => {
this.productList.push(item);
});
})
})
console.log(this.productList);
}
When I try console.log(this.productList);
, my expected outcome should be:
[{
"product_name": "Product One",
"product_information": {
"template_details": [
{
"template_name": "RACE Template",
"productProperties": [
{
"property_id": 2518427931,
"property_name": "Length",
"property_value": "12 cm"
},
{
"property_id": 2621195440,
"property_name": "Width",
"property_value": "10 cm"
},
{
"property_id": 2621195441,
"property_name": "Height",
"property_value": "20 cm"
}
]
}
]
}
},
{
"product_name": "Product Two",
"product_information": {
"template_details": [
{
"template_name": "RACE Template",
"productProperties": [
{
"property_id": 2518427931,
"property_name": "Length",
"property_value": "15 cm"
},
{
"property_id": 2621195440,
"property_name": "Width",
"property_value": "12 cm"
},
{
"property_id": 2621195441,
"property_name": "Size",
"property_value": "Medium"
}
]
}
]
}
}]
Instead, I only get an empty array []..
How can I ensure that the data is stored in productList
only after the service has completed?
I need to use forEach with this.product_id.forEach(element
to retrieve the product list for each product id sent through the URL in my actual application..
Please assist me in storing the data in productList
only after all product ids have been processed and the final product list is obtained..
Working stackblitz: https://stackblitz.com/edit/flatternstructure-dvzpjv
Once again, I emphasize that in my real application, I need to pass the id to retrieve the product value
like
https://api.myjson.com/bins/hiolc + element
..
Furthermore, once I have the final productList
, I need to perform additional functionality with it, which is why I expect the complete data in productList
at the end and not within the forEach
loop..