我在函数之间共享变量几乎没有问题。在我的情况下,我首先调用函数watchLocation(),它用于更新位置变量,每次调用setLocation()时,我都需要将位置变量传递给此函数,但变量仍为空。也许我做错了什么但对我来说是有意义的。
我的代码在这里:
export class LocationComponent {
@ViewChild("mapbox") _mapbox: ElementRef;
player_latitude:string;
player_longitude:string;
constructor() {
this.player_latitude;
this.player_longitude;
}
watchLocation() {
let watchId = watchLocation(
function (loc) {
if (loc) {
this.player_latitude = loc.latitude;
this.player_longitude = loc.longitude;
}
},
function(e){
console.log("Error: " + e.message);
},
{desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime : 1000 * 20});
}
setLocation() {
alert(this.player_latitude);
this._mapbox.nativeElement.setCenter({
lat: this.player_latitude,
lng: this.player_longitude,
animated: true
});
}
}
答案 0 :(得分:2)
使用()=>{}
代替function () {}
,然后this.
将起作用
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions