0

我已经按照 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);
    });
}

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

4

1 回答 1

0

我和@Kaws有同样的问题

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

解决方案是使用chenkie建议的 observable

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);
  }
于 2017-09-05T08:56:29.720 回答