Got This Is Null

Viewed 86

I got some weird error "this is null". I don't know what the problem is. This my demo Stackblitz.com and example code as your reference.

Component

ngOnInit() {
    this.getCurrentLocation();
  }

  getCurrentLocation() {
   navigator.geolocation.getCurrentPosition(position =>{
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.weatherInfo(this.lat, this.lng)
},function(){
       this.origin = { lat: '3.140853', lng: '2.693207'};
       console.log(this.origin)
       this.weatherInfo(this.origin.lat, this.origin.lng)
})



  }
  weatherInfo(lat, lng){
    console.log(lat, lng);
  }
2 Answers

You need to use an arrow function (() => { instead of function() {) due to the required scope:

getCurrentLocation() {
   navigator.geolocation.getCurrentPosition(position =>{
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.weatherInfo(this.lat, this.lng)
}, () => { // Here
       this.origin = { lat: '3.140853', lng: '2.693207'};
       console.log(this.origin)
       this.weatherInfo(this.origin.lat, this.origin.lng)
})

Maybe worth a read: Understanding "this" in javascript with arrow functions or Arrow functions and the ‘this’ keyword

You either need to bind this on your anonymous function or write it as an arrow function so your reference to this remains.

Option 1:

getCurrentLocation() {
// Your Method
}, this.logging().bind(this))

logging() {
// Do something
}

Option 2:

getCurrentLocation() {
// Your Method
}, () => {// Do something})
Related