我有一个简单的 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/