等到两个Observables完成 [英] Wait until two Observables are complete

查看:60
本文介绍了等到两个Observables完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在两个Observables返回值之后调用一个方法.我做了一些搜索,看来forkJoin是我想要的,但我无法使它正常工作.我知道这两个Observable都返回值,因为我在组件中其他每个地方分别使用数据,所以很明显我在做其他错误.

I want to call a method after two Observables have returned values. I did some searching and it seems like forkJoin is what I want, but I can't get it to work. 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.

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

Here is what I tried. I'm using 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),
);

什么都没有记录到控制台,并且我没有收到任何错误.同样,我传递的Observable肯定是返回值.

Nothing is logging to the console and I am not getting any errors. Again, the Observables I am passing in are definitely returning values.

我是在做错什么,还是我完全通过使用forkJoin采取了错误的方法?

Am I doing something wrong, or am I taking the wrong approach entirely by using forkJoin?

推荐答案

forkJoin在所有可观察对象完成时发出,而不是在它们发出时发出.

forkJoin emits when all the observables complete, not when they emit.

您可以改用combineLatest.

请注意不要'rxjs/operators'导入实例运算符.这是由某些IDE自动导入功能引起的常见错误.在这种情况下,我们需要从'rxjs'导入的静态版本:

Be careful to not import the instance operator from 'rxjs/operators'. It's a common mistake caused by some IDEs auto-import feature. In this case, we need the static version, imported from '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),
);

这篇关于等到两个Observables完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆