Angular + RxJS:如何对数组中的每一项进行并行请求?

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

我有一组 ID。例如:[1,2,3,4].

我想进行并行调用并为数组的每个元素获取 forkJoin 的结果。但是下面的代码对我不起作用。

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);
}); 

谁能帮我实现这个目标?谢谢

试试这个:

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

你快到了。 forkJoin 函数需要一个可观察对象的数组或对象。所以你只需要 return 来自 Array#map 函数的可观察对象。默认情况下使用 Angular HttpClient returns 的 HTTP 调用是可观察的。所以不需要 mergeMap 运算符。

这里mergeMap的用法也是错误的。它 return 是 OperatorFunction and not an observable

尝试以下方法

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

另外,如果您不知道的话,默认情况下,带有单个语句且不带大括号的箭头函数 return 是语句。

所以下面

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

等同于写

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