【问题标题】:Service call in controller in AngularJs using ES6使用 ES6 在 AngularJs 中的控制器中的服务调用
【发布时间】:2016-10-24 03:28:06
【问题描述】:

我正在尝试使用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'];

【问题讨论】:

标签: javascript angularjs ecmascript-6


【解决方案1】:

我认为,当 getSuccess 被调用时,你的 this 上下文丢失了,你可以试试这个:

if (navigator.geolocation) {
        navigator.geolocation.watchPosition(
             this.geoSuccess.bind(this), 
             this.geoFailed.bind(this)
        );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 2017-10-11
    • 1970-01-01
    • 2018-09-29
    • 2017-12-08
    • 2015-05-14
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多