I have these 2 observables:
this.areasService.getSelectAreas({})
.subscribe((result) => this.areasSelect = result.json().data.areas);
this.stationsService.getSelectStations({})
.subscribe((result) => this.stationsSelect = result.json().data.stations);
that fills these 2 variables (async) this.areasSelect
& this.stationsSelect
.
I also have a 3rd observable that I need to have these values to continue:
this.transportsService.getTransport().subscribe((res) => {
console.log(this.areasSelect)
console.log(this.stationsSelect)
})
How can I combine these 3 observables?
All you need to do is to use forkJoin
, it will call both of your first async calls and only returns data on both completion , so no need to worry
After that on subscribe you will get result in array of sequence you called the urls or apis.
const combined = Observable.forkJoin(
this.areasService.getSelectAreas({}).map((res) => res.json().data.areas),
this.stationsService.getSelectStations({}).map((res) => res.json().data.stations)
)
combined.subscribe(latestValues => {
this.areasSelect = latestValues[0];
this.stationsSelect = latestValues[1];
this.transportsService.getTransport().subscribe((res) => {
console.log(this.areasSelect)
console.log(this.stationsSelect)
})
});
You could use forkJoin
:
import { forkJoin } from 'rxjs/observable/forkJoin';
let areaSelect$ = this.areasService.getSelectAreas({})
.map(res => res.json().data.areas)
.do(val => this.areaSelect = val);
let stationSelect$ = this.stationsService.getSelectStations({})
.map(res => res.json().data.stations)
.do(val => this.stationSelect = val);
forkJoin(areaSelect$,stationSelect$)
.mergeMap(data=>{
//data is an array with 2 positions which contain the results of the 2 requests. data[0] is the vale of this.areaSelect for example
return this.transportsService.getTransport(data[0],data[1]);
}).subscrite(res => {
// res is the response value of getTransport
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With