【问题标题】:How to convert a promise to an observable in Angular如何在 Angular 中将 Promise 转换为 observable
【发布时间】:2021-11-10 23:42:28
【问题描述】:

我应该将此 google 地理编码方法转换为 observable 吗?

如果是这样,我该怎么做?

仅供参考 - 我认为我不需要拒绝承诺,只需返回 null,所以我在下面做了一些小改动。

const geoCode = new Geocode();
geoCode.geocode('some address').then(place => {
  console.log(place.geometry.location);
})
.catch(err => {
  console.log(err);
});


export class Geocode {

  geocode(address: string): Promise<any> {
    const geocoder = new google.maps.Geocoder();
    return new Promise((resolve, reject) => {
      geocoder.geocode({
          address: address
        },
        (results, status) => {
          if (status === google.maps.GeocoderStatus.OK) {
            resolve(results[0]);
          } else {
            // reject(new Error(status)); // don't need to reject
            resolve(null);
          }
        }
      );
    });
  }
}

【问题讨论】:

  • 这能回答你的问题吗? Convert Promise to Observable
  • 您的链接中有很多答案,这有点令人困惑/不知所措。不确定链接中的任何答案是否有帮助,因为未显示来自承诺的代码,而我的示例包含来自承诺的所有代码。
  • 好吧..阅读它们,尝试那些似乎与你的情况相匹配的,然后让我们知道你有什么具体问题
  • 也许更好的问题是,我将如何在 Angular 9/10 中等待 google goecoder?承诺还是可观察?
  • 你是说喜欢这个吗? stackoverflow.com/questions/56186253/…

标签: javascript angular promise observable


【解决方案1】:

试试这个:

  geocode(address: string): Observable<any> {
    const geocoder = new google.maps.Geocoder();
    return new Observable(subscriber => {
      geocoder.geocode({
          address: address
        },
        (results, status) => {
          if (status === google.maps.GeocoderStatus.OK) {
            subscriber.next(results[0]);
          } else {
            subscriber.next(null);
          }
          subscriber.complete();
        }
      );
    });
  }

【讨论】:

    猜你喜欢
    • 2016-08-15
    • 2017-04-04
    • 2021-12-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多