如何在Angular9中进行同步调用? |地理定位

How to make a synchronous call in Angular 9? | geolocation

已接受的解决方案 对我不起作用。我正在调用需要同步的位置服务,因为此后会立即对其执行 api 调用。

我的日志记录表明尽管有 await 子句,定位服务仍在返回 undefined

进行 api 呼叫的服务

...
@Injectable({providedIn: 'root'})
class PrepopulateService {
  constructor(private locationService: LocationService,
              private log: LoggerService) { }

  async prepopulate(): Promise<boolean> {
    const coords: string[] = await this.locationService.getLocation();
    console.log(coords)
    if(coords == null) {
      return false;
    }
    console.log(coords)
    // api call here
    return true;
  }
}

export { PrepopulateService }

为其获取位置的服务

...
@Injectable({providedIn: 'root'})
class LocationService {

  constructor(private log: LoggerService) { }

  getLocation(): Promise<string[]> {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        const longitude = position.coords.longitude;
        const latitude = position.coords.latitude;
        console.log([String(latitude), String(longitude)])
        return [String(latitude), String(longitude)];
      });
    } else {
      this.log.warn('No support for geolocation');
      return null;
    }
  }
}

export { LocationService }

我执行 async/await 有什么问题?

你没有return你的getLocation函数的承诺。

您应该从一个承诺中调用 navigator.geolocation.getCurrentPosition 并且 return 该承诺。然后,您在传递给 getCurrentPosition.

的回调中解决承诺
getLocation(): Promise<string[]> {
  return new Promise<string[]>((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(Error('No support for geolocation'));
      return;
    }

    navigator.geolocation.getCurrentPosition((position) => {
      const longitude = position.coords.longitude;
      const latitude = position.coords.latitude;
      resolve([latitude.toString(), longitude.toString()]);
    });
  });
}

DEMO:https://stackblitz.com/edit/angular-r6kq9q(模拟版本 getCurrentPosition