【问题标题】:Angular5 nested observable-subscriptions to a single observableAngular5 嵌套 observable-subscriptions 到单个 observable
【发布时间】:2018-09-15 03:22:35
【问题描述】:

我在服务层有如下代码,我有两个问题:

return this.equipmentService.getEquipment(this.id) //returns subscription
  .subscribe((equipment : Equipment) =>
  {
    this.getEquipmentTags(); //returns subscription
    this.getPredictions(); //returns subscription
  });
});
  1. 在代码中,我订阅了设备服务.getEquipment observable 和 现在它返回订阅对象 - 我怎样才能使它成为一个可观察的对象 再次,以便它可以在 业务层中再次处理,例如
  2. 我如何知道所有内部 observable 都完成了它们的任务并触发了一个事件(或调用方法或创建另一个我可以在代码中订阅的 observable)

【问题讨论】:

  • 取决于你想对结果做什么,有选择:Combining-Observables
  • 对于问题 1:我想退回设备,对于问题 2 - 我不在乎结果 - 我只需要知道他们完成了
  • 我查看了您提供的链接,但它是关于可观察对象的,我不知道如何将订阅对象再次变为可观察对象。
  • 我认为您在显示的代码中想要map(或flatmap)而不是subscribe。这样你只处理Observable 类型。之后可以再次添加subscribe,强制执行。

标签: angular nested observable subscription


【解决方案1】:

不要过早触发订阅,正如@igor 指出的那样,你(this.equipmentService.getEquipment(this.id) 不返回订阅,它返回一个 Observable,因为以其他方式你不能订阅它),使用 concatMap(和pipeable 操作符)来链接你的 Observables。

getChainedObservables() {
  return this.equipmentService.getEquipment(this.id)
    .pipe(
      concatMap((equipment : Equipment) => this.getEquipmentTags()),
      concatMap(() => this.getPredictions())
    );
}

然后调用它,

this.getChainedObservables().subscribe(console.log);

【讨论】:

    【解决方案2】:

    我认为您正在寻找的是主题。

    Subject 可以充当 Observable 或 Observer,因此您既可以订阅它,也可以调用 .next() 发送事件。它们还包含有用的方法,例如 complete()error(),可让您控制特定主题的状态。

    这里是a useful article,涵盖了该主题的基础。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多