【问题标题】:How to chain multiple subscriptions to an observable, within the observable, in rxjs?如何在 rxjs 中的 observable 中将多个订阅链接到 observable?
【发布时间】:2019-03-04 17:21:28
【问题描述】:

我想防止重复的 http 调用。我在一个 observable 上有多个订阅,并且那个 observable 有一个 switchMap 来决定是否会有一个 http 调用:

getModules(): Observable<Module[]> {
  return this.modules$.pipe(
    switchMap((modules: Module[]) => {
      if (!modules) {
        return this.setModules(); // http call, returning observable
      }
      return this.modules$; // observable
    })
  );
}

然后有多个订阅,在应用程序的不同组件中,调用此方法。如何防止多个 http 调用?我需要延迟调用 http observable,而不是延迟发出的值。

【问题讨论】:

  • 是否会在第一次调用之后在组件中设置一个布尔值,然后在执行任何 http 工作之前检查它?
  • 你想推迟到什么时候?顺便说一句 shareReplay()share() 所以也许其中一个可以帮助你。
  • @martin 我不想延迟值的发送。如果当前正在进行中,我想阻止 http 调用。我正在尝试像 Lazy Coder 建议的那样。

标签: javascript angular rxjs


【解决方案1】:

只需将Observable 存储为public 服务属性,而不是在代码中的任何地方调用getModules().subscribe(...),因为这样做会实例化多个Observable。 实际上,pipe 运算符在每次调用时都会生成一个新的 Observable

【讨论】:

  • 我尝试将 getModules() 的输出存储在构造函数中,但 http observable 仍然被多次调用。
  • 你只给getModules()打过一次电话?
【解决方案2】:

感谢@Lazy Coder,这是我解决此问题的方法: 我为 getModules() 添加了一个“忙碌”标志,并让订阅者保持打开状态,以便在 http observable 更新源模块 $ 时收到通知。

private getModules(): Observable<Module[]> {
    return this.modules$.pipe(
      switchMap((modules: Module[]) => {
        if (!modules && !this.isBusy) {
          return this.setModules(); // updates the modules$ source when complete
        }
        return this.modules$;
      })
    );
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 2019-09-15
    • 2017-10-10
    • 2020-02-25
    • 1970-01-01
    • 2016-12-20
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多