angular - 在两个 Observable 完成后做一些事情

标签 angular rxjs

我正在调用两个服务:

myfirstService.getCollections().subscribe(collection => myCollection = collection);

mysecondService.getCollectionId().subscribe(id => myId = id);

现在我需要根据 Id 从集合中获取项目,就像这样

mycollection.find(x => x.id == myId);

当然这应该在我得到collections和id之后再做。

Collection 和 Id 显示在 UI 中,所以我不想在另一个内部调用一个,我也不想等到两者都完成,因为我需要在交付后立即使用 collections 和 id。

只有在所有调用完成后才能获取对象。

最佳答案

您可以使用 tap 将发出的值分配给全局变量,只要您得到它。然后同时执行两个 Observables 并等待它们用 forkJoin 完成。

forkJoin(
  myfirstService.getCollections().pipe(
    tap(collection => myCollection = collection)
  ),
  mysecondService.getCollectionId().pipe(
    tap(id => myId = id)
  )
).subscribe(([collection, id]) => collection.find(x => x.id == id))

关于angular - 在两个 Observable 完成后做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57902367/

相关文章:

javascript - Ionic 2 Modal 不会关闭

Angular 2 - 影响主 socket 的辅助 socket 导航

angular - 如何防止在确认之前更改 MatTab?

angular - 将 rxjs 存储包含在 angular2/4 中的最佳实践/正确方法是什么,它应该在 Bootstrap 中还是导入中?

angular - RXJS 'never' 主题为泛型

angular - 同步函数 - 在 Angular 中

angular - 在 IIS 中部署 Angular 应用程序

angular - IdentityServer4 + ASP.NET 核心 API + Angular : Login/authentication

javascript - 在 RxJs 中使用 TestScheduler 测试 Subject

rxjs - Redux 可观察到的 : How to return an action from a callback?