Angular 如何等到订阅全部完成?
我有4个方法,每个方法都是在方法完成之前调用的。在所有这些服务器上,我都设置了这个:Angular 如何等到订阅全部完成?,angular,Angular,我有4个方法,每个方法都是在方法完成之前调用的。在所有这些服务器上,我都设置了这个:this.service.next('1');this.service.next('2');this.service.next('3');this.service.next('4')我使用它来知道哪个方法完成了,所以例如,有时我只执行3个方法,有时是1个,有时是全部。我的问题是,我订阅了其他组件,但它每次都进入订阅。我想要的是等待所有方法完成,然后调用this.service.next() 在所有的方法中,if-
this.service.next('1');this.service.next('2');this.service.next('3');this.service.next('4')代码>我使用它来知道哪个方法完成了,所以例如,有时我只执行3个方法,有时是1个,有时是全部。我的问题是,我订阅了其他组件,但它每次都进入订阅。我想要的是等待所有方法完成,然后调用this.service.next()
在所有的方法中,if-else语句都有一些逻辑
这是我的方法之一:
getOpenConnectionOnLoad(eventSourceId?: any) {
this.sharedData.block = 'ES';
this.api.get('/ccm/eventsource/customerESBlock-esId/' + eventSourceId + '?isVpn=true')
.subscribe(results => {
this.eventSourceInfo = results['payload'].eventsources[0];
Object.assign(this.sharedData.customer.eventSourceInfo, this.eventSourceInfo);
this.setConnectionIds();
this.customerNames = results['payload'];
Object.assign(this.sharedData.customer.customerNames, this.customerNames);
if (this.eventSourceInfo.saggId) {
this.openSagg(0, this.eventSourceInfo.saggId);
}
if (this.eventSourceInfo.baggId) {
this.getBaggById(this.eventSourceInfo.baggId);
}
this.showEs();
this.sharedData.customer.show = 7;
this.sharedData.callservice.next('2');
});
在其他组件中,我有:
this.sharedData.callservice.subscribe((data) => {
console.log('entry ');
});
然后,我只想输入一次,而不是4次。请查看forkjoin操作员:
此运算符将所有api调用作为参数传递,并在所有api调用返回数据时恢复
Observable.forkJoin([
this.http.get('https://your/api/call/1'),
this.http.get('https://your/api/call/2'),
]).subscribe(results => {
// results[0] is our result of first api call
// results[1] is our result of second api call
console.log(results[1]);
console.log(results[0]);
});
更新(感谢@HameedSyed)
在rxjs版本6+中,语法发生了更改:
import {forkJoin} from 'rxjs';
return forkJoin(
this.http.get('https://your/api/call/1'),
this.http.get('https://your/api/call/2'));