简体   繁体   中英

uncaught TypeError: Cannot set property value of null

Cannot set property 'currentLat' of null; I tried declaring all the variables globally so I can use the later but I don't know why I keep getting null when I call a variable and try to set its properties.

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 is not available in your nested function. You can bind this like onSuccess.bind(this); to the function or easily assign this to another variable.

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

Use arrow functions to access "this" variable:

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

The value of this is null since you are using it inside the function. You could use arrow functions instead.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM