首页 > 解决方案 > 未捕获的类型错误:无法设置 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');
        }
    }

标签: javascriptangulartypescript

解决方案


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

推荐阅读