[英]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.