我有4个方法,每个方法都在方法完成之前调用。在所有这些我设置这个: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次
答案 0 :(得分:4)
查看 forkjoin 运算符:
此运算符使所有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]);
});
在rxjs版本6+中,语法发生了变化:
import {forkJoin} from 'rxjs';
return forkJoin(
this.http.get('https://your/api/call/1'),
this.http.get('https://your/api/call/2'));