angular - 如何在 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 }
我的异步/等待实现有什么问题?
解决方案
你没有从你的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
)
推荐阅读
- java - Spring JdbcTemplate - 如何预先为实现多租户的每个查询?
- javascript - 用画布中的形状动画线条
- ruby-on-rails - 当同一模型有两个 has_one 关联时,Rails 5 Form 无法正确保存
- javascript - 执行exe时在nodejs中显示弹出消息或进度条
- javascript - 在 ReactJS 中获取窗口位置
- delphi - FMX TEdit 在键盘为 Microsoft 拼音时出现不良行为
- azure - 仅在生产中使用 Azure 网络安全组而不是独立防火墙是否合适?
- javascript - 将弹出框放在 noUiSlider 手柄上
- javascript - 角度指令上的正则表达式仅返回 false
- vue.js - 在 DOM 更改之前使用 vue-router 更改路由时触发事件?