Dheeraj Agrawal Dheeraj Agrawal - 1 month ago 12
AngularJS Question

Service call in controller in AngularJs using ES6

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'];

Answer

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