Mic*_*lis 5 observable rxjs angular
我有这两个可观测量:
this.areasService.getSelectAreas({})
.subscribe((result) => this.areasSelect = result.json().data.areas);
this.stationsService.getSelectStations({})
.subscribe((result) => this.stationsSelect = result.json().data.stations);
Run Code Online (Sandbox Code Playgroud)
填充这两个变量(异步)this.areasSelect&this.stationsSelect.
我还有一个第三个observable,我需要继续这些值:
this.transportsService.getTransport().subscribe((res) => {
console.log(this.areasSelect)
console.log(this.stationsSelect)
})
Run Code Online (Sandbox Code Playgroud)
我如何组合这3个可观察量?
你可以使用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
})
Run Code Online (Sandbox Code Playgroud)