【问题标题】:Angular2: Access class variable within anonymous functionAngular2:匿名函数中的访问类变量
【发布时间】:2019-02-11 11:46:48
【问题描述】:

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

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 变量。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    不要使用function (),因为它会改变this的范围。

    箭头函数保留this的范围

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

    【讨论】:

      【解决方案2】:

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

      onSuccess:(result: any) => {
              this.authService.login(this.user, result);
      }
      

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

      var self = this;
      
      onSuccess: function(result: any) {
          self.authService.login(this.user, result);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-24
        • 1970-01-01
        • 2020-08-19
        • 2014-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-11
        相关资源
        最近更新 更多