接受的解决方案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 }
我的异步/等待实现有什么问题?
您没有从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
)] >>