Search code examples
angularrxjsangular11mergemap

Angular + RxJS: How to make parallel request for each item in an array?


I have an array of IDs. For eg: [1,2,3,4].

I would like to make parallel calls and get the result with forkJoin for each element of the array. But below code is not working for me.

forkJoin(
  Array.from(this.question.attachments).map(attachment => {
    return mergeMap((attachment) => ) // i am stuck here.
  })
)
.pipe(
  takeUntil(this.destroy$),
  finalize(() => this.spinnerService.hide())
)
.subscribe((attachmentIds) => {
  this.uploadedAttachments = attachmentIds;
  this.onFilesAttached.emit(this.uploadedAttachments);
}); 

Can anyone help me how to achieve this? Thanks


Solution

  • You're almost there. forkJoin function expects an array or object of observables. So you only need to return the observable from the Array#map function. HTTP calls using Angular HttpClient returns an observable by default. So there is no need for the mergeMap operator.

    Also the usage of mergeMap is wrong here. It returns an OperatorFunction and not an observable.

    Try the following

    forkJoin(
      Array.from(this.question.attachments).map(attachment => 
        this.someService.getIds(attachment)                    // <-- return the HTTP call here
      )
    ).pipe(
      ...
    

    Also in case if you weren't aware, an arrow function with a single statement without curly braces returns the statement by default.

    So the following

    Array.from(this.question.attachments).map(attachment => 
      this.someService.getIds(attachment)
    )
    

    is same as writing

    Array.from(this.question.attachments).map(attachment => {
      return this.someService.getIds(attachment);
    })