12

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.

2 Answers 2

31

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);
    },
Sign up to request clarification or add additional context in comments.

Comments

12

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.