angular - 使用异步等待获得角度位置的最佳方法是什么?
问题描述
这是我的代码,工作正常,但很难看。我的目标是在服务中做到这一点。但首先当我把异步等待功能不起作用:
看一下这个:
ngOnInit() {
this.getLocation();
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.position = position;
this.makeSomething_1();
this.makeSomething_3();
this.makeSomething_4();
}, positionError => {
console.log('The user don accept location.');
this.makeSomething_1();
this.makeSomething_3();
this.makeSomething_4();
});
} else {
console.log('Geolocation is not supported by this browser.');
this.makeSomething_1();
this.makeSomething_3();
this.makeSomething_4();
}
}
但我想做这样的事情:
ngOnInit() {
this.getLocation();
this.makeSomething_1();
this.makeSomething_3();
this.makeSomething_4();
}
async getLocation() {
if (navigator.geolocation) {
await navigator.geolocation.getCurrentPosition(position => {
this.position = position;
}, positionError => {
console.log('The user don accept location.');
});
} else {
console.log('Geolocation is not supported by this browser.');
}
}
我想要的问题是 this.position 打印“未定义”
有人可以教我如何编写好的代码吗?
请不要给我-1。我尽力了
解决方案
最快的方法是使用 RxJS 多播 observable 将结果缓存在服务中,例如ReplaySubject
.
尝试以下
服务
import { ReplaySubject } from 'rxjs';
export class LocationService {
private positionSource = new ReplaySubject(1); // <-- buffer 1
public position$ = this.positionSource.asObservable();
constructor() {
this.getLocation();
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.makeSomething_1();
this.makeSomething_3();
this.makeSomething_4();
this.positionSource.next(position);
}, positionError => {
console.log('The user don accept location.');
this.makeSomething_1();
this.makeSomething_3();
this.makeSomething_4();
});
} else {
console.log('Geolocation is not supported by this browser.');
this.makeSomething_1();
this.makeSomething_3();
this.makeSomething_4();
}
}
}
零件
export class SomeComponent implements OnInit {
constructor(private _location: LocationService) { }
ngOnInit() {
this._location.position$.subscribe({
next: position => {
console.log('Got position: ', position);
// do something else with `position`
}
});
}
}
推荐阅读
- dart - Dart - 通过映射构造函数实例化泛型类型
- pandas - 计算两个日期之间的周末数(周六和周日)
- python-3.x - 自定义 NER Spacy 抛出 IndexError:列表索引超出范围
- javascript - 无法从日期获取小时数
- go - 从 Go 中的符文中获取 unicode 脚本
- arrays - Swift 结构体
- rust - 如何使用lazy_static!在结构 impl 中?
- prolog - 如何使此函数返回坐标而不是空列表
- kubernetes - 添加审计策略文件参数后没有出现 apiserver
- docker - 无法从 docker 容器访问主机 VPN