我正在尝试使用Weakmap()
在控制器中调用服务,但它的错误为Cannot read property 'getWeather' of undefined
。以下是我的代码:
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'];
答案 0 :(得分:2)
我认为,调用getSuccess时你的这个上下文会丢失,你可以试试这个:
if (navigator.geolocation) {
navigator.geolocation.watchPosition(
this.geoSuccess.bind(this),
this.geoFailed.bind(this)
);
}