这是我的代码,运行良好,但很难看。我的目标是在服务中做到这一点。但首先,当我放置异步等待功能时,它不起作用:
看看这个:
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.');
}
}
我想要的问题是这个位置打印";未定义的";
有人能教我如何写好代码吗?
请不要把我放在-1。我尽力了
最快的方法是使用RxJS多播可观察的(如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`
}
});
}
}