我需要在我的 Angular 应用程序中进行嵌套的 http 调用。第一次调用返回 field 列表,然后使用每个 field ID 我必须进行多次 api 调用以获取每个 field 的详细信息。这是我的代码,
服务.ts
GetResponse(){
return this.http.get('someurl')//Returns list of venues
.map(res => res.json())
.flatMap(
(result) =>{
return
Observable.forkJoin(result.response.groups[0].items.map
((data) => this.getDetailss(data))
)});
}
getDetailss(venues) {
return this.http.get('some url'/venues.id)// returns details of single venue
}
组件.ts ,
this.service.GetResponse().subscribe(
(response)=> console.log(response),//Prints array of observables
(error)=>console.log(error)
);
我在我的组件中接收到一组可观察值。我如何以 json 形式从中检索数据?
最佳答案
如果您想要所有地点
详细信息的数组,您可以使用combineLatest
运算符:
this.http.get('someurl')
.map(res => res.json())
.flatMap(result => {
const venueRequests = [];
for (const venue of result.someproperty) {
venueRequests.push(this.http.get('someurl' + venue.id))
}
//This will change an Observable<Response>[] into an Observable<Response[]>
return Observable.combineLatest(venueRequests);
});
然后您可以简单地订阅它并添加 .map (res => res.json())
然后您将获得一组 地点
详细信息。
关于angular - 在 Angular 中进行嵌套 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45454224/