组合多个Observable

时间:2017-06-18 13:04:28

标签: angular rxjs observable

我有这两个可观测量:

this.areasService.getSelectAreas({})
   .subscribe((result) => this.areasSelect = result.json().data.areas);
this.stationsService.getSelectStations({})
   .subscribe((result) => this.stationsSelect = result.json().data.stations);

填充这两个变量(异步)this.areasSelect& this.stationsSelect

我还有一个第三个观察者,我需要继续这些值:

this.transportsService.getTransport().subscribe((res) => {
     console.log(this.areasSelect)
     console.log(this.stationsSelect)
})

如何组合这3个可观测量?

2 个答案:

答案 0 :(得分:4)

您需要做的就是使用forkJoin,它会调用您的第一个异步调用,并且只会在完成时返回数据,因此无需担心

在订阅之后,您将获得您调用urls或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)
    })
});

答案 1 :(得分: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
})