1

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?

4
  • Can you make a demo on stackblitz? Commented Jul 7, 2020 at 14:32
  • What is the response type of this.dataService.getData method ? An Observable from an HttpClient.get request ? Commented Jul 7, 2020 at 14:38
  • @ThierryFalvo yes, exactly Commented Jul 7, 2020 at 16:08
  • @martin I'll make it if Thierry's answer won't work. Commented Jul 7, 2020 at 16:09

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response, I'm now trying to implement it to my code. Will update you when I'm done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.