2016-10-24 1 views
2

Я пытаюсь вызвать услугу в контроллере с помощью Weakmap(), но его сообщение об ошибке Cannot read property 'getWeather' of undefined. Ниже мой код:Сервисный вызов в контроллере в AngularJs с использованием ES6

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

Возможный дубликат [Как получить доступ к правильной \ 'это \ '/ context внутри обратного вызова?] (http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – zeroflagL

ответ

2

Я думаю, ваш это - контекст теряется, когда getSuccess называется, вы можете попробовать это:

if (navigator.geolocation) { 
     navigator.geolocation.watchPosition(
      this.geoSuccess.bind(this), 
      this.geoFailed.bind(this) 
     ); 
} 
Смежные вопросы