Javascript 未捕获的TypeError:无法设置null的属性值
无法将属性“currentLat”设置为null;我尝试全局声明所有变量,以便可以使用后面的变量,但我不知道为什么在调用变量并尝试设置其属性时总是得到nullJavascript 未捕获的TypeError:无法设置null的属性值,javascript,angular,typescript,Javascript,Angular,Typescript,无法将属性“currentLat”设置为null;我尝试全局声明所有变量,以便可以使用后面的变量,但我不知道为什么在调用变量并尝试设置其属性时总是得到null currentLat: any; currentLng: any; ngOnInit() { this.watchPosition(); } watchPosition() { var options = { maximumAge: 3600000,
currentLat: any;
currentLng: any;
ngOnInit() {
this.watchPosition();
}
watchPosition() {
var options = {
maximumAge: 3600000,
timeout: 3000,
enableHighAccuracy: true,
}
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
this.currentLat=position.coords.latitude;
this.currentLng=position.coords.longitude ;
};
function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
}
使用箭头函数访问“this”变量:
onSuccess = (position) => {
this.currentLat=position.coords.latitude;
this.currentLng=position.coords.longitude ;
}
此
在嵌套函数中不可用。您可以绑定this
像onSuccess.bind(this)将代码>分配给函数,或轻松地将此分配给另一个变量
watchPosition() {
const that = this;
const options = {
maximumAge: 3600000,
timeout: 3000,
enableHighAccuracy: true,
};
const watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
that.currentLat = position.coords.latitude;
that.currentLng = position.coords.longitude ;
}
function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
}
此
的值为空,因为您正在函数中使用它。您可以改用箭头函数
watchPosition() {
var options = {
maximumAge: 3600000,
timeout: 3000,
enableHighAccuracy: true,
}
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
onSuccess = (position) => {
this.currentLat=position.coords.latitude;
this.currentLng=position.coords.longitude ;
};
onError = (error) => {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
}
我在你的代码中到处都找不到实际分配
。请发布相关代码。我更新了我的代码,请参阅。很简单,这在本文中不可用。阅读这里这是我的问题的答案是什么?以这种方式实现箭头函数
,您将在typescript找不到名称[functionName]