Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获的TypeError:无法设置null的属性值_Javascript_Angular_Typescript - Fatal编程技术网

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

Javascript 未捕获的TypeError:无法设置null的属性值,javascript,angular,typescript,Javascript,Angular,Typescript,无法将属性“currentLat”设置为null;我尝试全局声明所有变量,以便可以使用后面的变量,但我不知道为什么在调用变量并尝试设置其属性时总是得到null currentLat: any; currentLng: any; ngOnInit() { this.watchPosition(); } watchPosition() { var options = { maximumAge: 3600000,

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

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

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

在嵌套函数中不可用。您可以绑定
this
onSuccess.bind(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');
  }
}

的值为空,因为您正在函数中使用它。您可以改用箭头函数

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

我在你的代码中到处都找不到
实际分配
。请发布相关代码。我更新了我的代码,请参阅。很简单,这在本文中不可用。阅读这里这是我的问题的答案是什么?以这种方式实现
箭头函数
,您将在typescript
找不到名称[functionName]