Объект профиля из auth0 пуст до загрузки страницы

Я следовал за документацией 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;
        });
    }
}

Вот метод getProfile из auth.service,

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);
    });
}

После входа в систему я получаю сообщение об ошибке "Токен доступа должен существовать для получения профиля", но если я перезагружаю его, я его не вижу.

1 ответ

У меня была та же проблема, что и у @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);
  }
Другие вопросы по тегам