Pravu
Pravu

Reputation: 608

Got This Is Null

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

Upvotes: 3

Views: 114

Answers (2)

pzaenger
pzaenger

Reputation: 11984

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

Upvotes: 5

mamichels
mamichels

Reputation: 639

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

Upvotes: 2

Related Questions