我尝试使用 Weakmap()
调用 Controller 中的服务,但出现错误,无法读取未定义的属性“getWeather”
。下面是我的代码:
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'];
最佳答案
我认为,当调用 getSuccess 时,您的 this - 上下文会丢失,您可以尝试以下操作:
if (navigator.geolocation) {
navigator.geolocation.watchPosition(
this.geoSuccess.bind(this),
this.geoFailed.bind(this)
);
}
关于javascript - 使用 ES6 的 AngularJs Controller 中的服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40210294/