Как сделать синхронный звонок в Angular 9? | геолокации - PullRequest
0 голосов
/ 24 февраля 2020

Принятое решение здесь у меня не сработало. Я звоню в службу определения местоположения, которая должна быть синхронной, потому что сразу после этого на нем выполняется вызов 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 }

Что не так с моим реализация async / await?

1 Ответ

1 голос
/ 24 февраля 2020

Вы не возвращаете обещание из своей функции 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)

...