在加载页面之前,auth0 中的配置文件对象为空



我已经按照 auth0 的文档来实现个人资料图片和其他个人资料数据。auth0 中的配置文件对象为空,直到加载页面。 这是我从导航栏组件调用配置文件数据的代码,

ngOnInit() {
if (this.auth.userProfile) {
this.profile = this.auth.userProfile;
return;
}
if (this.auth.authenticated) {
this.auth.getProfile((err, profile) => {
this.profile = profile;
});
}
}

这是来自auth.service的getProfile方法,

public getProfile(cb): void {
const accessToken = localStorage.getItem('access_token');
if (!accessToken) {
throw new Error('Access token must exist to fetch profile');
}    
const self = this;
this.auth0.client.userInfo(accessToken, (err, profile) => {
if (profile) {
self.userProfile = profile;
}
cb(err, profile);
});
}

登录后,我收到错误"访问令牌必须存在才能获取配置文件",但如果我重新加载它,我看不到它。

我遇到了与@Kaws相同的问题

它在教程中有效,但是当我尝试在我的解决方案中实现它时,我想在存储访问令牌之前加载的导航栏中显示"昵称"。

对此的解决方案是使用 chenkie 建议的可观察量

AuthService.ts:

import { Observable, Observer } from 'rxjs';
// ...
private observer: Observer<string>;
userImageChange$: Observable<string> = new Observable(obs => this.observer = obs);
// ...
public handleAuthentication(): void {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
window.location.hash = '';
this.setSession(authResult);
this.getProfile();
this.router.navigate(['/controlpanel']);
} else if (err) {
this.router.navigate(['/controlpanel']);
console.log(err);
}
});
}
public getProfile(): void {
const accessToken = localStorage.getItem('access_token');
if (!accessToken) {
throw new Error('Access token must exist to fetch profile');
}
const self = this;
this.auth0.client.userInfo(accessToken, (err, profile) => {
if (profile) {
this.observer.next(profile.picture);
}
});
}

然后在组件中的 getProfile 调用中:

userImage: string;
constructor(private auth: AuthService) {}
ngOnInit() {
this.auth.userImageChange$.subscribe(image => this.userImage = image);
}

最新更新