Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Access class variable within anonymous function

I'm sure there is a simple way to do this but I can't seem to find it. Here is my code

export class UserLoginComponent {
private user: User;
public authService: AuthService;

constructor(private cognitoConfigs: CognitoUtil, authService: AuthService) {
    this.user = new User();
    this.authService = authService;
}

authenticate() {

    // Some work being done here
    let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);

    cognitoUser.authenticateUser(authenticationDetails, {

        onSuccess: function(result: any) {
            this.authService.login(this.user, result);
        },
        onFailure: function(err: any) {
            console.log(err.message);
        },

    });

}
}

Problem: In the onSuccess callback I can't access the this.authService variable which belongs to it's parent class.

like image 351
Joshua Kissoon Avatar asked Sep 19 '16 14:09

Joshua Kissoon


2 Answers

Don't use function () because it changes the scope of this.

Arrow functions retain the scope of this

    onSuccess: (result: any) => {
        this.authService.login(this.user, result);
    },
    onFailure: (err: any) => {
        console.log(err.message);
    },
like image 54
Günter Zöchbauer Avatar answered Oct 29 '22 00:10

Günter Zöchbauer


The problem here is that the success callback function is in a different lexical environment. This is why in ES6+ functions can be defined using arrow functions =>.

onSuccess:(result: any) => {
        this.authService.login(this.user, result);
}

or assign this to a variable outside the scope of the function with the ES5 syntax:

var self = this;

onSuccess: function(result: any) {
    self.authService.login(this.user, result);
}
like image 27
Mini Bhati Avatar answered Oct 28 '22 22:10

Mini Bhati