首页 > 解决方案 > 如何在 Angular 9 中进行同步调用?| 地理位置

问题描述

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

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

进行 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 }

我的异步/等待实现有什么问题?

标签: angulartypescriptpromiseasync-awaitgeolocation

解决方案


你没有从你的getLocation函数中返回一个承诺。

您应该navigator.geolocation.getCurrentPosition从承诺中调用并返回该承诺。然后,您在传递给的回调中解决承诺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()]);
    });
  });
}

演示:https ://stackblitz.com/edit/angular-r6kq9q (带有模拟版本getCurrentPosition


推荐阅读