等到两个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),
);