等待两个 Observable 完成

2024-01-08

我想在两个 Observables 返回值后调用一个方法。我做了一些搜索,看起来像forkJoin是我想要的,但我无法让它发挥作用。我知道这两个 Observables 都返回值,因为我在组件中的其他地方单独使用每个 Observables 的数据,所以显然我做错了其他事情。

这是我尝试过的。我正在使用 rxjs v6.4。

forkJoin(
  this.store.pipe(select(fromStore.getAppointmentsLoading)),
  this.clientStore.pipe(select(fromClientStore.getClientsLoading)),
).subscribe(
  ([res1, res2]) => {
    console.log('res1', res1);
    console.log('res2', res2);
  },
  err => console.error(err),
);

没有任何内容记录到控制台,并且我没有收到任何错误。同样,我传入的 Observables 肯定会返回值。

我是否做错了什么,或者我是否完全使用了错误的方法forkJoin?


forkJoin当所有可观察量完成时(或其中一个抛出错误时)发出,而不是当它们发出时发出。

您可以使用combineLatest反而。

小心not从中导入实例运算符'rxjs/operators'。这是某些 IDE 自动导入功能导致的常见错误。在这种情况下,我们需要静态版本,导入自'rxjs':

import {combineLatest} from 'rxjs';

combineLatest([
  this.store.pipe(select(fromStore.getAppointmentsLoading)),
  this.clientStore.pipe(select(fromClientStore.getClientsLoading)),
]).subscribe(
  ([res1, res2]) => {
    console.log('res1', res1);
    console.log('res2', res2);
  },
  err => console.error(err),
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

等待两个 Observable 完成 的相关文章

随机推荐