繁体   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