[英]Retuning values from HTTP POST instead of Observable
我正在开发一个基于城市的 angular 应用程序。
place_id
值。place_id
getPlacesPhotoRef
应该返回 10 张照片参考。 我想要做的是,我希望将photo ref
推送到照片的数组。
预计 output。
{
formatted_address: 'xxx',
place_id: 'xxx',
photos: [...] //All 10 photo ref
}
但问题是,我看到 Observable 在照片数组中返回,而不是值。
下面是我的代码
getPlaceId(cityName) {
let httpPath = `http://localhost:5001/calvincareemailservice/us-central1/webApi/api/v1/getplaces`;
return this.http.post(httpPath, { city: cityName }).subscribe(res => {
if (res) {
let data = JSON.parse(JSON.stringify(res));
this.placeIds.push({
formatted_address: data.candidates[0].formatted_address,
place_id: data.candidates[0].place_id,
photos: this.getPlacesPhotoRef(data.candidates[0].place_id)
.subscribe(res => {
let data = JSON.parse(JSON.stringify(res));
return data.result.photos.map(pic => pic.photo_reference);
})
}
);
}
});
}
getPlacesPhotoRef(id) {
let httpPath = `http://localhost:5001/calvincareemailservice/us-central1/webApi/api/v1/getplacesid`;
return this.http.post(httpPath, { placeId: id })
}
您非常接近并且正确地考虑了这个问题,但问题是您已经为您的photos
键分配了一个 Observable 订阅,而不是.subscribe()
实际返回的数据,我想这就是您希望自己在做的事情。
在高层次上,您要做的是将新的 object 推送到this.placeIds
,一旦您拥有它需要的所有信息,例如formatted_address
、 place_id
和photos
。 所以你需要在这里做的是:
/getplaces
端点并存储地点数据data.candidates[0].place_id
调用/getplacesid
端点并存储照片数据this.placeIds
嵌套.subscribe()
调用的简单示例:
getPlaceId(cityName) {
const httpPath = `http://localhost:5001/calvincareemailservice/us-central1/webApi/api/v1/getplaces`;
return this.http.post(httpPath, { city: cityName })
.subscribe(res => {
if (res) {
const data = JSON.parse(JSON.stringify(res));
const formatted_address = data.candidates[0].formatted_address;
const place_id = data.candidates[0].place_id
this.getPlacesPhotoRef(place_id)
.subscribe(res => {
const data = JSON.parse(JSON.stringify(res));
const photos = data.result.photos.map(pic => pic.photo_reference)
this.placeIds.push({
formatted_address,
place_id,
photos
})
})
);
}
});
}
注意:更优雅的方法是使用concatMap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.