【发布时间】:2019-09-26 03:09:16
【问题描述】:
我有如下数据:
[
{
id: 1,
pets: [
{
id: 11,
pet: 'Zebra'
},
{
id: 12,
pet: 'Giraffe'
}
]
}
]
我从获取请求中获得。对于数组和pets数组中的每个项目,我需要根据id从另一个端点获取每个pet的mood,例如返回:
{
id: 11,
mood: 'hungry'
}
所以请求后的最终结果是这样的:
[
{
"id": 1,
"pets": [
{
"id": 11,
"pet": "Zebra",
"mood": "hungry"
},
{
"id": 12,
"pet": "Giraffe",
"mood": "happy"
}
]
}
]
我已尝试对所有pets 使用forkJoin,但无法使其正常工作。 Stackblitz 下面是一种尝试:
getCombined() {
return of(this.parent).pipe(
switchMap(families => {
return families.map(family => {
return forkJoin(
family.pets.map(pet => {
return this.getMood(pet.id).pipe(
map(data => {
pet.mood = data.mood;
return family;
})
)
})
)
})
}), switchMap((d) => d)
);
}
它正确地返回了 3 个外部对象,但它们看起来都是同一个对象。如何得到正确的结果?在此先感谢,这里是 Stackblitz:https://stackblitz.com/edit/angular-ttpcvu?file=src%2Fapp%2Fapp.component.ts
【问题讨论】: