在 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();

任何方向都值得赞赏。

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

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

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

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

我从 Auth0 官方页面尝试教程并修改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

最新更新