【问题标题】:uncaught TypeError: Cannot set property value of null未捕获的类型错误:无法设置 null 的属性值
【发布时间】:2019-03-07 01:42:02
【问题描述】:

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

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用箭头函数访问“this”变量:

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

    【讨论】:

    • 这是我的问题的答案是什么?
    【解决方案3】:

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

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

    【讨论】:

    • 以这种方式实现arrow functions,你会在打字稿Cannot find name [functionName]中得到一个错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多