Combining several observables

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); 

which populates these 2 variables (asynchronous) this.areasSelect & this.stationsSelect .

I also have a third 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?

+5
source share
2 answers

You can 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 }) 
+3
source

All you have to do is use forkJoin , it will call both of your first asynchronous calls and only return data upon completion, so no need to worry

After that, on the subscription, you will get the result in an array of the sequence that you called 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) }) }); 
+4
source

Source: https://habr.com/ru/post/1268951/


All Articles