首页 > 解决方案 > 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

标签: angulartypescript

解决方案


您的代码问题在函数中使用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);
    } );
  }

推荐阅读