I have a nested for loop and internal loop also makes service calls in angular 2
public populateData: any[] = [];
let appCounter = 0;
this.list.forEach(data => { <---- outer loop
this.service.getSubs(data.id).subscribe(res => { <---- backend call to get data
let subscriptions = res.subscriptions;
subscriptions.forEach(subscription => {
if(condition){
this.populateData.push(subscription);
}
});
});
appCounter++;
if(appCounter == this.list.length){
console.log('--------- subscriptionList ----------');
console.log(this.populateData);
}
});
I want to call a method after populateData variable is populated by executing outer loop completely.
currently, it gives me empty array in the console, because outer loop executes completely while inner HTTP calls are still pending.
promisesare here for you, more preciselyPromise.all. Or you can do it the old school way by incrementing a variable inside the callback and test if all responses arrived, so you can trigger the rest of the code (all this inside the callback, except the var that needs not to loose its value between steps)appCountervariable ingetSubsservice call, it prints value equal to size ofthis.list, because even for first service call outer loop is executed andappCounteris incremented.