javascript - 如何在 Angular 7 中管理多个可观察对象

标签 javascript angular typescript rxjs angular7

我有一个 angualr 7 应用程序,总共有 20 个传感器数据。我想每 5 秒使用 observable 为选定的传感器 ID 接收一次数据。例如;

var sensorId = ""; // dynamically selected from the web UI
var sensorData$ = interval(5000).pipe()
sensorData$.subscribe() // etc..

我将选择多个传感器,并开始使用间隔订阅获取数据。我怎样才能保留这些观察值?我该如何管理它?

此外,我可以随时添加任何传感器。

最佳答案

我建议使用 Subject 和 mergeMap。

至于解释,您将有 1 个主题,当用户从 UI 中选择一个时,您将在其中发出新的 sensorId。然后您需要订阅那个确切的主题,并且在 mergeMap 的帮助下,您将在订阅方法中拥有所有传感器值。

让我们看一下演示代码:

private sensorIdSubject = new Subject();

ngOnInit() {
  this.sensorIdSubject.pipe(
    mergeMap(sensorId => 
      interval(5000).pipe(switchMap(() => this.getSensorData(sensorId)))
  ).subscribe(sensorData => {
    // Every 5 second, each of the sensorIds that have been selected in UI will 
    // get sensor data and emit new value here in subscribe, because all of them
    // have been merged.
  })
}

public chooseSensor(sensorId) {
  this.sensorIdSubject.next(sensorId);
}

这个合适吗?我会根据您的需要更新我的代码,请在评论部分告诉我。

关于javascript - 如何在 Angular 7 中管理多个可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57073941/

相关文章:

javascript - 从 typescript 模块自动生成 index.d.ts,类型定义

javascript - .then() 尝试在 promise 解决之前运行

asp-classic - 服务器端 javascript - 经典 asp

javascript - setTimeout、jQuery 操作、transitionend 随机执行/触发

angular - Google Tag Manager JS 错误触发器不适用于 Angular App

angular - 获取当前组件名称

Angular Service Worker - Rest API 数据

javascript - 如何在 Google 文档脚本中加粗一行?

Angular 响应式(Reactive)表单自定义验证 : update on change not working on first time

angular - 如何在 Ionic 2 或 3 应用程序中加载实际图像之前显示占位符图像