【问题标题】:Rxjs prevent subscribe in subscribeRxjs 阻止订阅中的订阅
【发布时间】:2020-03-02 16:22:12
【问题描述】:

我有一个对象数组。我需要获取数组 if ids,然后调用 2 个 API,然后关闭模态窗口。

我的代码是:

from(this.alerts)
      .pipe(map(alert => alert._id))
      .subscribe(alertIds => zip(
          this.alertApi.someCall1(alertIds, ...),
          this.alertApi.someCall2(alertIds, ...),
        ).subscribe(() => {
          this.activeModal.close();
        }),
      );

您对防止subscribe 进入subscribe 有任何想法吗?

【问题讨论】:

  • this.alerts 是具有_id 属性的对象数组吗?

标签: javascript angular rxjs rxjs6 subscribe


【解决方案1】:

使用switchMaprxjs 操作符来避免嵌套订阅。

from(this.alerts)
      .pipe(
         map(alert => alert._id),
         switchMap(alertIds => zip(
           this.alertApi.someCall1(alertIds, ...),
           this.alertApi.someCall2(alertIds, ...)
         ))
      )
      .subscribe(() => {
          this.activeModal.close();
      );

更多关于 switchMap 操作符的信息可以在here找到。

【讨论】:

  • 请注意,当 observable 返回错误时,此解决方案还将调用 close()
【解决方案2】:

您可以使用forkJoin,类似于Promise.allswitchMap

See also: the RxJS docs, specifically example 6, which is similar to your situation.

from(this.alerts)
    .pipe(
        switchMap(alert =>
            forkJoin(
                this.alertApi.someCall1(alert._id),
                this.alertApi.someCall2(alert._id)
            )
        )
    )
).subscribe(() => {
   this.activeModal.close(); 
});

请注意,只有在所有内部 observable 都完成时,才会发出结果 observable。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多