angular - Angular - 从方法中提取或读取值并将其保存以供以后使用
问题描述
我需要保存坐标 lat n lon 中的值,以便在此 .TS 文件中的其他方法中使用它们。但是当我到达该"let x = pos.coords;"
部分时,它给了我一个错误“TypeError:无法读取null的属性'LAT'”。似乎我失去了价值,或者我无法访问 LAT n LOG 变量来保存它们
在我的“menu.component.ts”里面
public LAT:any;
public LON:any;
ngOnInit() {
navigator.geolocation.getCurrentPosition(success)
function success(pos: { coords: any; }) {
let x = pos.coords;
this.LAT = x.latitud;
this.LON = x.longitud;
}
}
并且,当在 LAT n LOG 上保存值时,我如何在其他方法上调用它们......比如this.LAT
?
解决方案
您的代码问题在函数中使用this
,将您的代码更改为以下
ngOnInit() {
navigator.geolocation.getCurrentPosition((pos: { coords: any }) => {
let x = pos.coords;
this.LAT = x.latitude;
this.LON = x.longitude;
console.log(this.LAT, this.LON);
}, error => {
console.error(error);
} );
}
推荐阅读
- ios - 我想线程化从 iOS 中的领域读取的数据
- linux - Elasticsearch 集群未显示
- python - 从熊猫日期时间列中提取年份作为数值,用 NaN 表示空单元格而不是 NaT
- python - 在循环中将从字符串转换为浮点数的数字列表相乘(Python)时遇到问题
- python - 有没有办法在不涉及任何内容的情况下在谷歌中输入 python 类型?
- java - 在不传入根对象的情况下读取嵌套的 yaml 值
- c# - 实体框架未检测 c# 中的 jsonb 属性更改
- sql - 为 sum() 选择一半的分区
- php - php wordpress $_POST 增量简码
- javascript - 如何防止 PHP 应用程序中的恶意 POST 请求?