我正在开发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();
任何方向都值得赞赏。
答案 0 :(得分:1)
我不知道您为什么要订阅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触发了click事件,您就可以获取会话数据。因此,如果您需要电子邮件,请尝试this.currentUser.email
答案 1 :(得分:1)
问题在于,您的console.log(this.currentUser)
在将值发送到您的订阅之前已得到执行。
如果您按以下方式更改代码,则它应该可以工作:
this.auth.userProfile$.subscribe(userProfile => {
this.currentUser = userProfile;
console.log(this.currentUser);
});