简体   繁体   English

为 Angular 编写 Geolocation API 作为 promise 或 observable

[英]Write Geolocation API as promise or observable for Angular

I am using Angular 6 and need to get location data in a promise.我正在使用 Angular 6,需要在承诺中获取位置数据。 The geolocation API has a callback for success and error navigator.geolocation.getCurrentPosition(successCallback, errorCallback); geolocation API有一个成功和错误回调navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

w3c Geolocation APIw3c 地理定位 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);
};

How would I write a promise or observable for Angular that utilized the success and error callbacks?我将如何为利用成功和错误回调的 Angular 编写承诺或可观察对象?

In Observable way, 以可观察的方式

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

You can create an async typescript function to return a new promise 您可以创建一个异步打字稿函数以返回新的Promise

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);
});

I don't know if there is a better way to do it, but this seems to work. 我不知道是否有更好的方法可以这样做,但这似乎行得通。

avoid using type "any"避免使用类型“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)
      );
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM