简体   繁体   English

如何从promise方法中访问角度js控制器的“this”?

[英]How can I access the “this” of an angular js controller, from inside a promise method?

I have simple angular js controller making a XHR request as below 我有简单的角度js控制器,如下所示发出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');
        }
    );

}]);

When I wrote this controller using $scope instead of this the code worked, now the this.php_response property is not containing the data retrieved from the XHR request. 当我使用$scope而不是代码编写此控制器时,现在this.php_response属性不包含从XHR请求中检索的数据。
I suspect the promise.then#success callback is no longer referencing the controller this . 我怀疑promise.then#success callback不再引用控制器this
How can I get access the this, inside the promise method? 如何在promise方法中访问它?

Use arrow function that preserves lexical context: 使用保留词汇上下文的箭头函数

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

Another simple way is to bind context with Function.prototype.bind method: 另一种简单的方法是使用Function.prototype.bind方法绑定上下文:

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

And finally, old-school way: define reference variable pointing to outer this and use it inside callback: 最后,老派的方式:定义引用变量指向外this ,并用它里面的回调:

var self = this;

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

Whatever you prefer more. 无论你喜欢什么。

You can also use angular.bind for this case 在这种情况下,您也可以使用angular.bind

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM