简体   繁体   English

等待两个 Observable 完成

[英]Wait until two Observables are complete

I want to call a method after two Observables have returned values.我想在两个 Observable 返回值后调用一个方法。 I did some searching and it seems like forkJoin is what I want, but I can't get it to work.我做了一些搜索,似乎forkJoin是我想要的,但我无法让它工作。 I know both of these Observables are returning values, as I am using the data for each individually elsewhere in the component, so clearly I'm doing something else wrong.我知道这两个 Observable 都在返回值,因为我在组件的其他地方单独使用每个数据,所以很明显我做错了其他事情。

Here is what I tried.这是我尝试过的。 I'm using rxjs v6.4.我正在使用 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),
);

Nothing is logging to the console and I am not getting any errors.没有任何内容记录到控制台,我也没有收到任何错误。 Again, the Observables I am passing in are definitely returning values.同样,我传入的 Observable 肯定是返回值。

Am I doing something wrong, or am I taking the wrong approach entirely by using forkJoin ?我做错了什么,还是我完全通过使用forkJoin采取了错误的方法?

forkJoin emits when all the observables complete (or when one of them throws an error), not when they emit. forkJoin在所有 observable 完成时(或当其中一个抛出错误时)发出,而不是在它们发出时发出。

You can use combineLatest instead.您可以改用combineLatest

Be careful to not import the instance operator from 'rxjs/operators' .注意不要'rxjs/operators'导入实例操作'rxjs/operators' It's a common mistake caused by some IDEs auto-import feature.这是由某些 IDE 自动导入功能引起的常见错误。 In this case, we need the static version, imported from 'rxjs' :在这种情况下,我们需要从'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),
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM