未捕获的TypeError:无法将属性值设置为null

时间:2019-03-06 16:48:22

标签: javascript angular typescript

无法将属性'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');
        }
    }

3 个答案:

答案 0 :(得分:2)

this在嵌套函数中不可用。您可以将thisonSuccess.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');
  }
}

答案 1 :(得分:0)

使用箭头功能访问“此”变量:

onSuccess = (position) => {
    this.currentLat=position.coords.latitude;
    this.currentLng=position.coords.longitude ;
}

答案 2 :(得分:0)

this的值为空,因为您正在函数内部使用它。您可以改用 箭头功能

 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');
        }
    }