Joshua Kissoon Joshua Kissoon - 1 year ago 93
TypeScript Question

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.

Answer Source

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

Array functions retain the scope of this

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