【问题标题】:Scope of $http callback in ES6ES6 中 $http 回调的作用域
【发布时间】:2016-04-10 02:50:05
【问题描述】:

我正在尝试编写一个使用 ES6 和 Angular 调用 API 的快速测试——但我无法完全弄清楚如何将注入的值限定在回调中——在所有情况下,它们似乎都是完全隔离的。有什么建议吗??

class Test {

constructor($state) {
    this.$state = $state;
}

doThing() {
    var request = this.$http({
        method: "get",
        url: "https://blah,
        params: {
            action: "get"
        }
    });
    return ( request.then(this.handleSuccess, this.handleError) );
}

handleSuccess(response) {
    update $state...
    this.$state is undefined
    this is undefined
}

handleError(response) {
    update $state...
}
}

Test.$inject = ['$state'];

【问题讨论】:

标签: angularjs ecmascript-6 es6-promise angularjs-http


【解决方案1】:

来自 Felix 的出色链接让我到达了我需要去的地方 - 不是 100% 确信这是最好的方法,但它至少相当干净。 HandleSuccess 和 HandleError 也被更改为接受可选范围。

    return ( request.then((response)=> {
        this.handleSuccess(response, this)
    }).catch((response)=> {
        this.handleError(response, this)
    }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多