2016-09-30 66 views
2

我试图在用户通过Firebase登录后设置配置文件页面路由。我的signin组件包含通往profile路径的路径。这里唯一的问题是我的配置文件组件具有来自Firebase数据库的用户数据。结果,当我重定向到我的个人资料页面时,出现错误Cannot read property 'uid' of null重新启用配置文件页面w /用户数据Angular2和Firebase

如果我在登录后刷新页面,那么我的个人资料页面会出现没有错误。

signin.component.ts

signInSubmit(){ 
    var self = this; 
    firebase.auth().signInWithEmailAndPassword(self.signInForm.value.smail, self.signInForm.value.spassword).catch(function(error){ 
    console.log(error.message); 
    }); 
    localStorage.setItem('confirmo', 'verdad'); 
    self.router.navigate(['profile']); 
    } 

profile.component.ts

ngOnInit(){ 
    var self = this; 
    let user = firebase.auth().currentUser; 
    let userNamePath = `users/${user.uid}/username`; 
    let notesPath = `users/${user.uid}/addnote`; 

this.username$ = this.af.database.object(userNamePath); 
this.addsnotes$ = this.af.database.list(notesPath); 

function redis(){ 
    self.proshow = true; } 
    setTimeout(redis, 3000); 
} 

要尝试解决这个问题,我把超时显示我的个人资料组件之前。但是,这不起作用。即使我把我的整个ngOnInit放在超时功能中,也会出现相同的错误。

此外,我的一部分profile.component.html如果有帮助。

<h4>Welcome {{ (username$ | async)?.$value }}</h4> 

回答

0

答案竟然是全能的onAuthStateChanged。像这样:

profile.component.ts

ngOnInit(){ 
var self = this; 
firebase.auth().onAuthStateChanged(function(user){ 
if (user){ 
var userNamePath = `users/${user.uid}/username`; 
var notesPath = `users/${user.uid}/addnote`; 

self.username$ = self.af.database.object(userNamePath); 
self.addsnotes$ = self.af.database.list(notesPath); 
self.proshow = true; 
} 
}); 

}

相关问题