Geolocation: ERROR TypeError: Cannot set property 'lat' of null

Geolocation: ERROR TypeError: Cannot set property 'lat' of null

简介

我正在开发一个 Angular 应用程序,我想在其中获取用户的当前位置并将经度和海拔高度保存在两个属性 lnglat 中,但是这似乎不起作用,无论我尝试什么;我一直收到错误 ERROR TypeError: Cannot set property 'lat' of null

TypeScript 代码(相关部分)

  lat : any;
  lng : any;

  constructor() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(this.setValues);
    }
   }

  setValues(values) {
    this.lat = values?.coords?.latitude
    this.lng = values?.coords?.longitude;
  }

第一行setValues抛出错误

getCurrentPosition

返回的JSON对象的(相关部分)
{
  coords:
  {
    latitude: 27.380583,
    longitude: 33.631839
  }
}

我试过的

所有这些尝试都导致了同样的错误。

我不是 100% 确定问题出在哪里,但它与范围有关,通过创建匿名回调函数似乎可以正常工作。


  constructor() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((values) => { 
        this.lat = values?.coords?.latitude
        this.lng = values?.coords?.longitude;
      });
    }
   }

您可以使您的函数匿名:

  setValues = (values) => {
    this.lat = values?.coords?.latitude
    this.lng = values?.coords?.longitude;
  }

问题在于 this 在不同范围内所指的内容。当您使用箭头函数时,它仅指外部范围(在本例中为组件)。否则 this 指的是函数本身。

您可以通过设置以下测试亲眼看到它的实际效果:

ngOnInit() {

  // 1. delegate function
  this.getValues(this.setValues);

  // 2. function() { }
  this.getValues(function(values) {
    console.log(this);
  });

  // 3. arrow function
  this.getValues(values => this.setValues(values));
}

getValues(callback: (values) => void) {
  callback({
    lat: 1,
    long: 2
  });
}

setValues(values) {
  console.log(this);
}

这显示了将函数作为回调传递的 3 种不同方式。 1. 和 2. 将 undefined 记录到控制台。 3. 将记录包含 class(在我的演示中为 AppComponent)。

演示:https://stackblitz.com/edit/angular-c8eypx