假设我有一个旧代码,我不想更改它。我有三个服务器调用来获取一些数据,并且在这三种方法都成功之后我必须运行一些代码。我添加了变量,我想听听它的变化(ngOnChanges 不起作用)。
这是代码:
ngOnInit() {
this.loadedReq = 0; // When this var is 3 - then all requests passed, and i have to run some custom code, how to watch on this variable?
this.getCars();
this.getModels();
this.getTypes();
}
getCars() {
return this.myService.getCars(this.clientId)
.subscribe((response) => {
this.loadedReq++;
});
}
getModels() {
return this.myService.getModels(this.clientId)
.subscribe((response) => {
this.loadedReq++;
});
}
getTypes() {
return this.myService.getTypes(this.clientId)
.subscribe((response) => {
this.loadedReq++;
});
}
someMethodWhenAllLoaded(){}
有可能吗?不改变方法(我的意思是在响应等上实现巨大的 RxJs 逻辑)?
如果没有,那么如何在这里创建解决方法?
有很多不同的方法来做,但你可以做的一件事是使用.zip()
RxJs的操作符等待它们全部完成。
我们也保存了对它的引用,以便我们也可以取消订阅 onDestroy。
zippedSubs$: Subscription;
ngOnInit() {
this.zippedSubs$ = Observable.zip([
this.getCars(),
this.getModels(),
this.getTypes()
]).subscribe(result => {
console.log('All 3 are done!');
});
}
ngOnDestroy() {
this.zippedSubs$.unsubscribe();
}
getCars() {
return this.myService.getCars(this.clientId);
}
getModels() {
return this.myService.getModels(this.clientId);
}
getTypes() {
return this.myService.getTypes(this.clientId);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句