简体   繁体   中英

Wait for all iterations of foreach to complete in Angular when code in foreach returns observable

So I have a foreach loop on a bunch of rows and I'm calling API in this loop. Now I want to wait until all the iterations have been completed and observables from all iterations have been returned and then execute some code.
I have not used forkjoin since i want the data to be updated on the UI as and when the observable is emitted and dont want to wait until all the observables emit but at the same time I want to do some processing once all of them have emitted.

selected.foreach((row) => {
this.xyzservice(row).subscribe({
    next: .... do stuff....
}
)
})

You can use a for cycle and async/await pattern:

for(let i in selected) {
   var res = await this.xyzservice(selected[i]).toPromise();
}

You can also use Promise.all

You can subscribe for each observable (and update the UI if you want) then group all the observables and subscribe when they are all finished.

const observables = []
selected.forEach(s => {
  const observable = getObservable();
  observable.subscribe(result => /* Do what you want here */)
  observables.push(observable)
}

forkJoin(observables).subscribe(allResult => /* */)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM