Dheeraj Agrawal Dheeraj Agrawal - 1 year ago 63
AngularJS Question

Service call in controller in AngularJs using ES6

I am trying to call a service in a controller using

, 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 Source

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

if (navigator.geolocation) {