Reputation: 9247
I have 4 methods and every of method is calling when method before finished. On all of them im setting this: this.service.next('1');this.service.next('2');this.service.next('3');this.service.next('4');
Im using this to know which method is finished so for example sometimes i will execute only 3 methods sometimes 1 and sometimes all. My problem is that i subscribe on other component but it enter every time in subscribe. What i want is to wait all of methods finished and then call that this.service.next()
.
In all of methods i have some logic with if else statement.
This is one of my methods:
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');
});
In other component i have this:
this.sharedData.callservice.subscribe((data) => {
console.log('entry ');
});
I want then entery only once and not 4 times
Upvotes: 2
Views: 7450
Reputation: 1330
Take a look at forkjoin operator:
This operator makes all the api calls passed as arguments and will resume when all return data.
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]);
});
In rxjs version 6+ the syntax changed:
import {forkJoin} from 'rxjs';
return forkJoin(
this.http.get('https://your/api/call/1'),
this.http.get('https://your/api/call/2'));
Upvotes: 5