如何在Angular 9中进行同步调用? |地理位置

问题描述 投票:0回答:1

接受的解决方案here对我不起作用。我正在拨打需要同步的定位服务,因为此后立即对其执行了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 }

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

angular typescript promise async-await geolocation
1个回答
1
投票

您没有从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()]);
    });
  });
}

DEMO:https://stackblitz.com/edit/angular-r6kq9q(带有模拟版本的getCurrentPosition)] >>

© www.soinside.com 2019 - 2024. All rights reserved.