2016-09-29 53 views
0

现在我有一个Angular 2项目,它需要用户的登录凭证,并将用户重新路由到我的配置文件组件。使用Angular2和Firebase登录数据填充页面的路径

home.component.ts

constructor(public router: Router){} 
    signInSubmit(){ 
    var self = this; 
    firebase.auth().signInWithEmailAndPassword(self.signInForm.value.smail, self.signInForm.value.spassword).catch(function(error){ 
    console.log(error.message); 
    }); 
    self.router.navigate(['profile']); 
    } 

其中profile表示与用户的火力地堡数据的页面(例如,他们的用户名)。我的问题是用户数据未被用户重定向时填充。他们必须刷新页面才能看到它填充。

profile.component.ts

export class ProfileComponent implements OnInit { 
private addsnotes$: FirebaseListObservable<string[]>; 
private username$: FirebaseObjectObservable<string>; 
addForm: FormGroup; 

constructor(private af: AngularFire){} 

ngOnInit(){ 
    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); 
} 
} 

profile.component.html

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

当我重定向到我的个人资料的路线,据我所知,user为空。但是,如果我只是刷新页面,这也不是问题。我如何检索并输出用户的重新路由数据?我也愿意考虑页面刷新选项,但我不确定如何刷新到Angular 2中的单独路由。

+1

当您使用的'user'数据 –

+0

一个'setTimeout'功能对我ngOnInit内的一切设置超时之后会发生什么,一旦被启动,那么,仍然会返回一个错误。 – abrahamlinkedin

回答

2

问题是您尝试使用凭据登录后立即重定向。您需要等待登录才能成功,然后才能重新路由。

signInWithEmailAndPassword承诺基于呼叫,也成功呼叫后返回用户信息。所以,你可以这样做:

firebase.auth().signInWithEmailAndPassword(
    self.signInForm.value.smail, 
    self.signInForm.value.spassword 
) 
    .then((userInfo) => { 
    // Login was successful, NOW redirect 
    self.router.navigate([ 'profile' ]); 
    }) 
    .catch((error) => { 
    // Do something, such as report the error on your sign in page 
    });