Auth0 回调在登录后未设置配置文件日期 Angular2



我有一个Angular 2应用程序,该应用程序使用auth0进行身份验证。我遇到的问题是,当成功登录成功时,似乎没有调用锁回调。只有在我手动刷新页面之后,个人资料数据才会发送到本地存储。

当用户登录时,我需要抓住该配置文件对象并在组件类中使用它。仅在成功登录后手动刷新页面之后,此代码才能起作用。这是我的代码(仅包括重要部分)。

auth.service

 lock = new Auth0Lock('.....9cNzyzJ3DZc2VpDyXSYF5', '.....12.auth0.com', {});
  user: any;
  constructor() {
    // Add callback for lock `authenticated` event
    this.user = JSON.parse(localStorage.getItem('profile'));
    this.lock.on("authenticated", (authResult:any) => {
      this.lock.getProfile(authResult.idToken, function(error: any, profile: any){
        if(error){
          throw new Error(error);
        }
        localStorage.setItem('id_token', authResult.idToken);
        localStorage.setItem('profile', JSON.stringify(profile));
        this.user = profile;
      });
    });
  }
  public login() {
    // Call the show method to display the widget.
    this.lock.show();
    console.log('login func');
  };

nav.component

constructor(private auth: Auth, private groupsService: GroupsService){
}
ngOnInit(){
    // need to access the profile object here. Ocject is correctly logged only after refreshing.
    console.log(JSON.parse(localStorage.getItem('profile')));
    this.groupsService.getGroups(this.userId).subscribe(groups => {
        this.groups = groups;
        // sort the groups
        this.groups.sort((a, b) => new Date(b.date_created).getTime() - new Date(a.date_created).getTime());
    });
}

根据 ngOnInit的文档:

ngOnInit首次检查了指令的数据结合属性,并在检查其任何子女之前都被调用。实例化时仅调用一次。

(强调是我的)

表明当它运行时,由于尚未处理身份验证,因此还没有可用的用户配置文件。如果您在身份验证后引起页面刷新,则用户配置文件已在Web存储中可用,并且手册刷新会导致ngOnInit执行,导致您描述的行为。

最新更新