【问题标题】:Angular + RxJS: How to make parallel request for each item in an array?Angular + RxJS:如何对数组中的每个项目进行并行请求?
【发布时间】:2022-01-24 05:32:15
【问题描述】:

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

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

【问题讨论】:

    标签: angular rxjs angular11 mergemap


    【解决方案1】:

    你快到了。 forkJoin 函数需要一个可观察的数组或对象。所以你只需要从Array#map 函数返回observable。使用 Angular HttpClient 的 HTTP 调用默认返回一个 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);
    })
    

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-29
        • 2022-01-25
        • 1970-01-01
        • 2018-06-20
        • 2018-10-21
        • 2015-06-26
        • 1970-01-01
        相关资源
        最近更新 更多