javascript - 如何从 promise 方法内部访问 Angular js Controller 的 "this"?

标签 javascript angularjs

我有一个简单的 Angular js Controller ,如下所示发出 XHR 请求

app.controller('MainController', ['$http', function($http) {

    this.php_response = {};

    var promise = $http.get('process.php');

    promise.then(
        function(success_data) {

            // I dont think "this" is talking to the controller this anymore?    
            this.php_response = success_data;

        }, function(error) {
            console.log('there was a problem');
        }
    );

}]);

当我使用 $scope 而不是此代码编写此 Controller 时,代码有效,现在 this.php_response 属性不包含从 XHR 请求中检索的数据。< br/> 我怀疑 promise.then#success 回调不再引用 Controller this
我怎样才能在 promise 方法中访问 this?

最佳答案

使用arrow function保留词汇上下文:

promise.then(success_data => {  
    this.php_response = success_data;
}, error => {
    console.log('there was a problem');
});

另一种简单的方法是将上下文与 Function.prototype.bind 绑定(bind)方法:

promise.then(function(success_data) {  
    this.php_response = success_data;
}.bind(this), function(error) {
    console.log('there was a problem');
});

最后,老派方法:定义指向外部 this 的引用变量并在回调中使用它:

var self = this;

promise.then(function(success_data) {  
    self.php_response = success_data;
}, function (error) {
    console.log('there was a problem');
});

你更喜欢什么。

关于javascript - 如何从 promise 方法内部访问 Angular js Controller 的 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274878/

相关文章:

javascript - 根据另一个数组的对象属性过滤 JavaScript 数组

javascript - Highcharts 气泡图数据标签中的居中文本

javascript - 使用 Redux 作为初始组件状态

javascript - Protractor 找不到 Angular

javascript - AngularJS - 从页面底部的远程服务器加载更多数据

angularjs - Firebase Storage 如何复制/复制存储的图像?

javascript - 正则表达式问题 : Difference between 'seconds?' and 'second(?:s)?'

类上的 JavaScript 单击事件监听器

angularjs - Ionic 框架 - 检测互联网连接

javascript - Angular : best way to provide local storage data? 在每个 Controller 中设置 rootScope?