在 Auth0 中检索用户配置文件信息

Retrieving User Profile Information in Auth0

我正在开发 Angular 8 SPA 并已成功集成 Auth0 身份验证。正如 Auth0 教程所示,显示每个用户的个人资料信息。请参阅下面的屏幕输出。如何在用户登录后访问电子邮件属性?

{
  "nickname": "user,
  "name": "user@email.com",
  "picture": "https://s.gravatar.com/user_image.png",
  "updated_at": "2020-01-15T17:39:10.467Z",
  "email": "user@email.com",
  "email_verified": true,
  "sub": "auth0|000000000000000000000000"
}

在 app.module.ts 中,我尝试使用以下方式订阅:

currentUser: string;
this.auth.userProfile$.subscribe(userProfile => {this.currentUser = userProfile});
console.log(this.currentUser);

但是,在控制台中我只得到:null。据我所知,auth.service.ts 提供了必要的可观察值:

private userProfileSubject$ = new BehaviorSubject<any>(null);
userProfile$ = this.userProfileSubject$.asObservable();

欢迎任何指导。

我不知道你为什么要订阅 app.module.ts,因为 auth.service.ts 提供了连接任何其他组件的可能性。

我尝试使用 Auth0 official page 中的教程并修改 home-content.component.ts 添加

// import section
import { AuthService } from 'src/app/auth/auth.service';

getSessionScope(){
    this.auth.userProfile$.subscribe(data => this.currentUser = data);
    console.log(this.currentUser);

  }

并在 home-content.component.html 添加

<button
      id="testButton"
      class="btn btn-primary btn-margin"
      (click)="getSessionScope()"
    >
      log session
    </button>

并且一旦通过 auth.service 触发了点击事件,您就可以获得会话数据。因此,如果您需要电子邮件,请尝试 this.currentUser.email

问题是您的 console.log(this.currentUser) 在值发送到您的订阅之前被执行。

如果您按如下方式更改代码,它应该可以工作:

this.auth.userProfile$.subscribe(userProfile => {
    this.currentUser = userProfile;
    console.log(this.currentUser);
});