Issue
I have implemented a function that I use to call an api, recover for each product some info and push into array. After that I have done this for all products, I would to do a action with the array.
So I have:
newProducts: any = []
loadOfferRelated(offer) {
// consider this offer with 2 products array.
let products = offer.products
for (let i = 0; i < products.length; i++) {
let apiCall = this.offerService.apiCall(products[i].id, product.catalogId)
apiCall.pipe(untilDestroyed(this)).subscribe(
(data) => { operationOnArray(data, products[i])}
)
}
if(this.newProducts.length > 0){
// ---> Here i should call another function but it doesn't enter there)
}
operationOnArray(data, product){
// I make some operation product and save in array
this.newProducts.push(products)
console.log("this.newProducts", this.newProducts) <-- this is every for populated + 1
return
}
I have a problem to call the if when the array newProducts is populated, how can I do?
Solution
Ok so you can use a forkJoin
, to make the api calls simultaneously and use the map
operator to return each transformed element, push the returned data into the array and then finally call the if condition.
newProducts: any = [];
loadOfferRelated(offer) {
// consider this offer with 2 products array.
let products = offer.products;
const apiCalls = products
.map((product: any) => this.offerService.apiCall(product.id, product.catalogId))
.pipe(
map((data: any, i: number) => {
// i am not sure what your doing with the api call (data) so I am merging product and data, you customize
// to your requirement
return { ...products[i], ...data };
})
);
forkJoin(apiCalls).subscribe((newProducts: Array<any>) => {
this.newProducts = newProducts;
if (this.newProducts.length > 0) {
// ---> Here i should call another function but it doesn't enter there)
}
});
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.