javascript - 未捕获的类型错误:无法设置 null 的属性值
问题描述
无法将属性“currentLat”设置为 null;我尝试在全局范围内声明所有变量,以便可以使用后者,但我不知道为什么在调用变量并尝试设置其属性时我一直为 null。
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
在您的嵌套函数中不可用。您可以将this
like绑定onSuccess.bind(this);
到函数或轻松分配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');
}
}
推荐阅读
- file - 如何在运行 rust 二进制文件之间将文件保存在内存中?
- firebase - 在 Flutter 列表视图中删除 Firestore 数据
- java - 尝试在后台线程上使用 Toast.hide 时出现 IllegalStateException
- python - 有没有办法在 Django 应用程序之外使用反向?
- excel - 为什么没有应用我的 VBE 颜色主题?
- ios - SwiftUI 如何实现 VKPinCodeView
- discord.js - Discord.js 如何添加角色
- python - 如何根据采样率在 Python 中按顺序对数组进行均匀采样?
- google-app-engine - post-install-cmd 在 Google App Engine 柔性环境中不起作用
- ruby - 如何比较来自两个不同数组的元素?红宝石