我遇到了这个代码的问题。我正在尝试从第二个端点收集与第一个get中返回集合中的id相关的额外详细信息。有人可以帮助如何获取实际数据,因为它返回一组可观察量。谢谢
this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
map((data: any) => data.cinemas),
map((cinemalist) => {
return cinemalist.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`));
})
).subscribe(results => {
console.log(results);
});
而不是map
,你可以用switchMap
做forkJoin
:
this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
map((data: any) => data.cinemas),
switchMap((cinemas) => forkJoin(cinemas.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`));
}))
).subscribe(results => {
console.log(results);
});
如果你想保留价值,你可以尝试这样的事情:
this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
map((data: any) => data.cinemas),
switchMap((cinemas) => forkJoin(cinemas.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`))
.pipe(map(cinema => {...cinema,value}))
}))
).subscribe(results => {
console.log(results);
});
this.http.get(`https://api.cinelist.co.uk/search/cinemas/location/${town}`).pipe(
map((data: any) => data.cinemas),
flatMap((cinemas) =>
forkJoin(
cinemas.map(value => {
return this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`).pipe(
map((result: any) => {
return { ...result, ...value };
}));
})
)
)
).subscribe(x => {
console.log(x);
});