我试图使多个http请求依赖于先前的请求,并将返回的数据组合到最终结果对象。
我有两个端点:
/properties
会给我类似的信息:
{
"data":[
{
"id":1,
"name":"Property 1",
"units":[
{
"id":1,
"name":"Property 1 - Unit 1",
},
{
"id":2,
"name":"Property 1 - Unit 2",
},
],
},
{
"id":2,
"name":"Property 2",
"units":[
{
"id":3,
"name":"Property 2 - Unit 3",
}
]
}
]
}```
/properties/${property.id}/units/${unit.id}/bookings
会向我返回一些与先前请求有关的对象,例如:
{
"data": {
"id": 1
},
"meta": {
"count": 5
}
}
我想实现的是将这两个响应合并为一个单元级别。像这样:
{
[
...
{
"id":2,
"name":"Property 2",
"units":[
{
"id":3,
"name":"Property 2 - Unit 3",
"bookings_meta": {
"count":5
}
}
]
}
]
}
我创建了类似的东西,并且效果很好:
list(): Observable<any> {
return this.http.get('/properties').pipe(
map((results: any) => results.data),
flatMap((properties: any[]) => {
if (properties.length > 0) {
return forkJoin(properties.map((property: any) => {
return forkJoin(property.units.map((unit: any) => {
return this.http.get(`/properties/${property.id}/units/${unit.id}/bookings`).pipe(
map(({ meta }) => {
unit.bookings_meta = meta
return unit;
})
)
}))
}))
}
return of([]);
})
);
}
this.list().subscribe(response => {
console.log(response)
})
但是我认为这不是100%正确的解决方案。我感觉forkJoin
太多,也许不应该在flatMap
那里?
[单位之间的预订的请求应该是独立的。
有人知道如何改进上面的代码?forkJoin
将在所有调用完成后返回数据并返回结果const combined = Observable.forkJoin(
this.http.get('https:// ...properties').map((res: Response) => res.json()),
this.http.get('https:// ..properties/${property.id}/units/${unit.id}/bookings')
.map((res: Response) => res.json())
)
combined.subscribe(latestValues => {
console.log( "latestValues" , latestValues );
});