将 Auth0 用户信息存储到 Angular2+ 服务中

Store Auth0 user info into Angular2+ service

我目前正在使用 Auth0 身份验证迁移现有的 Angular2+ 代码。 我不得不放弃锁定小部件以使用通用登录。

这是我使用 Auth0.js 的新服务示例:

  public infosUtilisateur: any = undefined;

  public RafraichirInfosUtilisateur()
  {
    let accessToken = localStorage.getItem('access_token');

    if(accessToken && !this.infosUtilisateur)
    {
      this.webAuth.client.userInfo(accessToken, function(err, user) 
      {
        this.infosUtilisateur = user; // Here goes the pain
      });
    }
  }

每当调用我的函数时,我都会收到此错误:

Cannot set property 'infosUtilisateur' of undefined

我不明白为什么我无法在 API 调用中访问我的服务 属性。

我做错了什么?

使用不带 function 关键字的 callback function 并使用 => insead。这会保留调用上下文。

if(accessToken && !this.infosUtilisateur)
{
  this.webAuth.client.userInfo(accessToken, (err, user) =>  
  {
    this.infosUtilisateur = user; // Here goes the pain
  });
}