考虑以下课程
class LoginController{
constructor(authService,$timeout,$state){
let vm = this;
this.loading = false;
this._authService = authService;
this._$timeout = $timeout;
this._$state = $state;
this.loading = false;
this.statusMessage = null;
}
login(){
this.loading = true;
this.statusMessage = null;
let loginModel = {
UserName : this.username,
Password : this.password,
RememberMe : this.rememberMe
};
//Login User
this._authService.login(loginModel).then(function(user){
//Set User Login & send to Dashboard
this._authService.setUser(user);
this._$state.go("dashboard");
}, function(error){
const errorMessage = error ? error.Message : "Undefined Login Issue occurred !";
this.loading = false;
});
}
}
一切都运行正常,除了那时我点击错误回调函数并且它到达this.loading = false;
由于某种原因这是未完成的。
如何保留对Class&#34的引用;这"在错误回调?
答案 0 :(得分:4)
你必须使用胖箭来保持范围。
//Login User
this._authService.login(loginModel).then((user) => {
//Set User Login & send to Dashboard
this._authService.setUser(user);
this._$state.go("dashboard");
}, (error) => {
const errorMessage = error ? error.Message : "Undefined Login Issue occurred !";
this.loading = false;
});
答案 1 :(得分:0)
function(error){
this.loading = false;
}
函数内部的这个是不同的范围,所以这是指函数而不是父函数。
解,
将此定义为self:
class LoginController{
constructor(authService,$timeout,$state){
let vm = this;
this.loading = false;
this._authService = authService;
this._$timeout = $timeout;
this._$state = $state;
this.loading = false;
this.statusMessage = null;
}
login(){
var self = this; //Define this as self
this.loading = true;
this.statusMessage = null;
let loginModel = {
UserName : this.username,
Password : this.password,
RememberMe : this.rememberMe
};
//Login User
this._authService.login(loginModel).then(function(user){
//Set User Login & send to Dashboard
self._authService.setUser(user);
self._$state.go("dashboard");
}, function(error){
const errorMessage = error ? error.Message : "Undefined Login Issue occurred !";
self.loading = false; //Self refers to this of parent scope
});
}
}
答案 2 :(得分:0)
这是将上下文传递给回调函数的一个非常常见的问题。通用答案是声明类似
的内容 var self=this;
在您想要保留的上下文中"此"
然后在你的回调函数中引用它就像这样
function callback () {
self.myvariable=true;
};
在你已经宣布的特定情况下
let vm = this;
所以你可以使用
vm._authService.setUser(user);
vm._$state.go("dashboard");