簡體   English   中英

從 HTTP POST 而不是 Observable 重新調整值

[英]Retuning values from HTTP POST instead of Observable

我正在開發一個基於城市的 angular 應用程序。

  1. getPlaceId function 將獲取 google place_id值。
  2. 基於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_addressplace_idphotos 所以你需要在這里做的是:

  1. 調用/getplaces端點並存儲地點數據
  2. 使用data.candidates[0].place_id調用/getplacesid端點並存儲照片數據
  3. 兩個端點都返回后,使用所有數據構造一個 object 並將這個 object 推送到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM