简体   繁体   中英

Angular 9 rxjs - forkJoin returns array of Observables instead of array of values

Here is a simplified version of my problem:

this.store.pipe(
  select(arr),
  switchMap(arr => {
    const data = arr.map(arrItem => this.dataService.getData(arrItem.id));
    return forkJoin(...data);
  }
  map(data => {
    console.log(data);
    return data;
  )
);

Somehow, in console.log I'm getting array of values only if arr.length = 1. If arr.length > 1, I'm getting array of Observables instead.

How is it possible? Am I misunderstanding forkJoin? How can I fix it?

If your service response is an observable and you want to retrieve an array of response at the end, you can do this:

this.store.pipe(
  select(arr),
  switchMap(arr => from(arr)),
  mergeMap(arrItem => this.dataService.getData(arrItem.id), 2),  // max 2 concurrents requests here
  toArray()
).subscribe(datas => {
  // datas is an array of returned data from getData service
});

Note here second argument of mergeMap (= 2 ), to specify maximum concurrent request.

switchMap(arr => from(arr)) : from an array value, to a new observable with emitted values = each value of the array

toArray() : take all values emitted, and transform to one array

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