【发布时间】:2018-03-12 20:50:46
【问题描述】:
我正在使用 typescript 并试图获取我们当前所在位置的地理位置。我可以获取位置,但我的代码在不设置位置的情况下继续。我决定使用 await 和 promise。我创建了一个如下所示的服务:
@Injectable()
export class GoogleMapsService {
private latitude: number;
private longitude:number;
public currentLongitude(): number {
return this.longitude;
}
public currentLatitude(): number {
return this.latitude;
}
constructor() {
this.setCurrentLocation();
}
private async setCurrentLocation() {
let location: GoogleLocation = await this.getLocation();
this.latitude = location.latitude;
this.longitude = location.longitude;
}
private getLocation(): Promise<GoogleLocation> {
let promise = new Promise<GoogleLocation>(() => {
let location = new GoogleLocation();
navigator.geolocation.getCurrentPosition(position => {
location.latitude = position.coords.latitude;
location.longitude = position.coords.longitude;
});
return location;
});
return promise;
}
}
所以我的问题是如何在等待时设置它。所以当我尝试访问它时它就在那里?
【问题讨论】:
-
so my question is how can I set this while i await it- 你想等待什么? -
让位置:GoogleLocation = await this.getLocation();
标签: angular typescript promise