Angular2:匿名函数中的Access类变量

Jos*_*oon 10 typescript angular

我确信有一种简单的方法可以做到这一点,但我似乎无法找到它.这是我的代码

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

    });

}
}
Run Code Online (Sandbox Code Playgroud)

问题:在onSuccess回调中,我无法访问this.authService属于它的父类的变量.

Gün*_*uer 23

不要使用,function ()因为它改变了范围this.

箭头功能保留范围 this

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


小智 10

这里的问题是成功回调函数处于不同的词法环境中.这就是为什么在ES6 +中可以使用箭头函数=>定义函数.

onSuccess:(result: any) => {
        this.authService.login(this.user, result);
}
Run Code Online (Sandbox Code Playgroud)

或使用ES5语法将此值分配给函数范围之外的变量:

var self = this;

onSuccess: function(result: any) {
    self.authService.login(this.user, result);
}
Run Code Online (Sandbox Code Playgroud)