Joshua Kissoon
Joshua Kissoon

Reputation: 3319

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.

Upvotes: 12

Views: 11308

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

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

Upvotes: 31

Mini Bhati
Mini Bhati

Reputation: 343

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

Upvotes: 12

Related Questions