javascript - 使用 ES6 的 AngularJs Controller 中的服务调用

标签 javascript angularjs ecmascript-6

我尝试使用 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/

相关文章:

javascript - 如何在 Bootstrap 下拉标题中显示带有图标的所选项目?

javascript - 将 div 的内容制作成可移动的可调整大小的按钮

javascript - 将 onPause/onResume 添加到 Ionic 2 页面中的 Youtube 视频

javascript - 将多个参数传递给 ng-click 方法

javascript - 替代多个 if 语句?

Javascript 在三个隐藏的 div 之间切换

javascript - 如何以 Angular 将参数传递给服务中的函数

javascript - 为什么作为箭头函数的方法在 react 类中起作用,但在普通类中不起作用?

javascript - 为什么我的 instanceof 运算符不响应 true?

javascript - 浏览器宽度调整上的 Jquery 更改脚本元素