ES6 + Angular控制器类,在回调中没有定义

ES6 + Angular Controller class, getting this is undefined in callback

本文关键字:回调 定义 Angular 控制器 ES6      更新时间:2023-09-26

考虑以下类

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;,由于某种原因,这是未定义的。

如何在错误回调中保留对类"this"的引用?

您必须使用胖箭头来保持范围。

//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;
});

将上下文传递给回调函数是一个非常常见的问题。一般的答案是声明像

这样的东西

var self=this;在您想要保留"this"的上下文中然后在回调函数中引用它,像这样

function callback () { self.myvariable=true; };

在你的特殊情况下,你已经声明了let vm = this;所以你可以用vm._authService.setUser(user); vm._$state.go("dashboard");

function(error){
    this.loading = false;
}

函数内部的this是一个不同的作用域,因此this指的是该函数而不是父函数。

解决方案,

定义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
        });
    }
}