我有 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');
});
Run Code Online (Sandbox Code Playgroud)
在其他组件中我有这个:
this.sharedData.callservice.subscribe((data) => {
console.log('entry ');
});
Run Code Online (Sandbox Code Playgroud)
我只想输入一次而不是四次
看一下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]);
});
Run Code Online (Sandbox Code Playgroud)
在 rxjs 版本 6+ 中,语法发生了变化:
import {forkJoin} from 'rxjs';
return forkJoin(
this.http.get('https://your/api/call/1'),
this.http.get('https://your/api/call/2'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7371 次 |
| 最近记录: |