Angular2:匿名函数中的访问类变量 [英] Angular2: Access class variable within anonymous function

查看:73
本文介绍了Angular2:匿名函数中的访问类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定有一种简单的方法可以做到这一点,但是我似乎找不到它.这是我的代码

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

    });

}
}

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

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

推荐答案

请勿使用function (),因为它会更改this的范围.

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

箭头功能保留this

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

这篇关于Angular2:匿名函数中的访问类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆