簡體   English   中英

如何從promise方法中訪問角度js控制器的“this”?

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

我有簡單的角度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');
        }
    );

}]);

當我使用$scope而不是代碼編寫此控制器時,現在this.php_response屬性不包含從XHR請求中檢索的數據。
我懷疑promise.then#success callback不再引用控制器this
如何在promise方法中訪問它?

使用保留詞匯上下文的箭頭函數

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

另一種簡單的方法是使用Function.prototype.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');
});

無論你喜歡什么。

在這種情況下,您也可以使用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