我按照auth0的文档来实现个人资料图片和其他个人资料数据。 auth0中的配置文件对象为空,直到加载页面。 这是我从navbar组件调用配置文件数据的代码,
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);
});
}
登录后,我收到错误'访问令牌必须存在以获取配置文件',但如果我重新加载它我就看不到它。
答案 0 :(得分:0)
我和@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);
}