2

I am trying to call a service in a controller using Weakmap(), but its giving an error as Cannot read property 'getWeather' of undefined. Below is my code:

const SERVICE = new WeakMap();

export default class WeatherController {
    constructor(apiService) {
        SERVICE.set(this, apiService);

        if (navigator.geolocation) {
            navigator.geolocation.watchPosition(this.geoSuccess, this.geoFailed);
        }
    }

    geoSuccess(position) {
        // This gives an error mentioned above
        SERVICE.get(this).getWeather(position.coords.latitude, position.coords.longitude);
    }

    geoFailed(err) {
        console.log('Error:', err);
    }
}

WeatherController.$inject = ['apiService'];
Dheeraj Agrawal
  • 2,347
  • 11
  • 46
  • 63
  • 1
    Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – a better oliver Oct 24 '16 at 07:31

1 Answers1

2

I think, your this - context is lost when getSuccess is called, You may try this:

if (navigator.geolocation) {
        navigator.geolocation.watchPosition(
             this.geoSuccess.bind(this), 
             this.geoFailed.bind(this)
        );
}
Dhananjaya Kuppu
  • 1,322
  • 9
  • 10