0

我有一组 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);
}); 

谁能帮助我如何实现这一目标?谢谢

4

2 回答 2

1

您快到了。forkJoin函数需要一个可观察对象的数组或对象。所以你只需要从Array#map函数中返回 observable。默认情况下,使用 Angular 的 HTTP 调用会HttpClient返回一个 observable。所以不需要mergeMap运营商。

这里的用法mergeMap也是错误的。它返回一个OperatorFunction而不是一个observable

尝试以下

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

另外,如果您不知道,默认情况下,带有单个语句且不带花括号的箭头函数会返回该语句。

所以以下

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

和写作一样

Array.from(this.question.attachments).map(attachment => {
  return this.someService.getIds(attachment);
})
于 2022-01-23T21:25:05.513 回答
0

试试这个:

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);
}); 
于 2022-01-23T20:22:55.650 回答