2016-12-09 26 views
3

我有一个角2应用程序使用auth0进行身份验证。我遇到的问题是,当发生成功登录时,似乎锁定回调没有被调用。只有在手动刷新页面后,配置文件数据才会发送到本地存储。auth0回调没有设置配置文件日期后登录angular2

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

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()); 
    }); 
} 
+0

嘿,我有同样的问题。你是如何解决这个问题的? – wuno

回答

1

按照documentation for ngOnInit

ngOnInit被称为指令的数据绑定属性已检查之后第一次,也是在任何孩子被检查之前。 当指令被实例化时,它仅被调用一次。

(重点是我的)

这表明当其运行没有可用的用户配置文件但因为仍然没有处理认证。如果您在认证后导致页面刷新,那么用户配置文件已经在网络存储中可用,并且手动刷新会导致执行ngOnInit,从而导致您所描述的行为。

+0

嗯,我也尝试把代码从ngOnInit放入构造函数中,并且它具有相同的效果。它应该去哪里? – jdoyle1331

+0

我的Angular2知识是有限的,但您需要以允许其他组件响应状态更改(用户配置文件可用性)的方式处理已认证的事件。检查这[问题/答案](http://stackoverflow.com/questions/34700438/global-events-in-angular-2)。 –

相关问题