【发布时间】:2017-07-31 23:02:15
【问题描述】:
我需要创建一个地理位置变量并将值发送到 API,但我很麻烦。
public virtualRegistrationHandler(e: any): void {
e.preventDefault();
console.log("loop");
if (navigator.geolocation) {
let geoLoc = navigator.geolocation.getCurrentPosition(this.setGeoLoc);
this.VirtualRegistrationService.virtualRegistration(geoLoc)
.subscribe(
response => this.toastyCommunicationService.addSuccesResponseToast(response),
error => this.toastyCommunicationService.addErrorResponseToast(error)
);
} else {
this.toastyCommunicationService.addErrorResponseToast("Geolocation is not supported by this browser.");
}
}
private setGeoLoc(position: any) {
console.log("Latitude " + position.coords.latitude, "Longitude " + position.coords.longitude);
let geoLoc = { "Latitude": position.coords.latitude, "Longitude": position.coords.longitude };
return geoLoc;
}
这是我当前的代码,但它不会等待返回 geoLoc,所以现在它会向 API 发送一个未定义的参数。
我想 API 调用等到geoloc 被设置。
我做了一些谷歌搜索,得到了一些承诺,但是我在编写语法时遇到了麻烦,我找不到任何可行的示例。
如何正确编写代码,以便在我的函数继续使用 API 之前必须先设置 geoLoc?
【问题讨论】:
标签: angular promise angular-promise