【问题标题】:Write Geolocation API as promise or observable for Angular将 Geolocation API 编写为 Angular 的 promise 或 observable
【发布时间】:2019-03-22 18:46:56
【问题描述】:

我正在使用 Angular 6,需要在 promise 中获取位置数据。 geolocation API 有一个回调成功和错误navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

w3c Geolocation API

[NoInterfaceObject]
interface Geolocation {
  void getCurrentPosition(PositionCallback successCallback,
  optional PositionErrorCallback errorCallback,
  optional PositionOptions options);

  long watchPosition(PositionCallback successCallback,
  optional PositionErrorCallback errorCallback,
  optional PositionOptions options);

  void clearWatch(long watchId);
};

如何为 Angular 编写一个利用成功和错误回调的 promise 或 observable?

【问题讨论】:

    标签: javascript angular callback promise observable


    【解决方案1】:

    您可以创建一个异步打字稿函数来返回一个新的承诺

    async getLocation() {
      return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
      });
    }
    
    const pos = this.getLocation();
    pos.then(res => {
      console.log(res);
    })
    .catch(err => {
      console.log(err);
    });
    

    我不知道是否有更好的方法,但这似乎有效。

    【讨论】:

    • async getLocation 那里不需要异步
    【解决方案2】:

    以可观察的方式,

    getLocation(): Observable<any> {
     return new Observable(obs => {
      navigator.geolocation.getCurrentPosition(
        success => {
          obs.next(success);
          obs.complete();
        },
        error => {
          obs.error(error);
        }
      );
    });
    }
    

    【讨论】:

      【解决方案3】:

      避免使用类型“any”

       getLocation() {
          return new Observable<GeolocationCoordinates>((observer) => {
            window.navigator.geolocation.getCurrentPosition(
              (position) => {
                observer.next(position.coords);
                // observer.complete() marks the observable as done. It means we can no longer emit any more values out of this observable
                observer.complete();
              },
              // observer.error puts observable into an error state. It means we can no longer emit any more values out of this observable
              (err) => observer.error(err)
            );
          });
        }
      

      【讨论】:

        猜你喜欢
        • 2021-06-23
        • 2021-07-06
        • 2016-08-15
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多