【发布时间】:2018-06-07 10:44:03
【问题描述】:
我正在尝试将 3 个 HTTP 请求合并为 1 个响应。
最后 2 个请求取决于第一个请求的数据。在阅读this post之后,我使用flatMap和forkJoin选择了以下方法。
作者使用的是旧版本的 Angular 和 RXjs,因此我对其进行了修改以使用管道运算符。但我仍然无法得到我需要的响应。
public getAllData(params): Observable<any> {
return this.http.get<any>(`${this.base}/seasons.json`, {params: params})
.pipe(
map((data: SeasonBase) => data.MRData.SeasonTable.Seasons),
flatMap((seasons: Season[]) => {
if(seasons.length > 0) {
return forkJoin(
of(seasons),
seasons.map((season: Season) => {
return this.http.get(`${this.base}/${season.season}/results/1.json`)
.pipe(
map((data: RaceBase) => data.MRData.RaceTable)
)
}),
seasons.map((season: Season) => {
return this.http.get(`${this.base}/${season.season}/driverStandings.json`)
.pipe(
map((d: any) => d.MRData.StandingsTable.StandingsLists[0])
)
})
).pipe(
map((data: any) => {
let season = data[0];
let races = data[1];
let standings = data[2];
season.testRaces = races;
season.standings = standings;
return season;
})
)
}
}),
catchError(this.handleError)
)
}
上述方法在订阅时返回如下响应:
我试图得到的响应应该更像这样:
{
season: "1950",
url: "http://en.wikipedia.org/wiki/1950_Formula_One_season",
testRaces: [test_races_data], // dont want observable
standings: [standings_data] // dont want observable
},
{...},
{...}
etc
testRaces 和 standings 作为 Observables 而不是响应返回。
是否可以在返回响应之前“解开”这 2 个 Obseravbles 以便我可以映射数据?
Here is a stackblitz 当前编写的代码。您可以检查开发工具控制台以查看响应。
【问题讨论】:
标签: javascript angular rxjs observable angular-http