Reputation: 7055
I am trying to get current user using angularfire2
. In my app.component.ts
file I have following code
constructor(private afAuth: AngularFireAuth, ) {
this.afAuth.auth.onAuthStateChanged((user) => {
if (!user) {
console.log("not login");
} else {
console.log("login");
}
});
this.initializeApp();
}
Now in my home page file I am trying to get with below code
CommonProvide.ts
constructor(private afAuth: AngularFireAuth) {
}
getUid() {
return this.afAuth.auth.currentUser.uid;
}
home.ts
constructor(private cp: CommonProvider) {
console.log(cp.getUid())
}
Now this returns undefined uid. Then I noticed that an ajax call goes that fetch user data from firebase. That's why my constructor got fired first before ajax end. If I run my home constructor after some delay I got response. Now how will I get usr id?
Upvotes: 1
Views: 1167
Reputation: 7055
I solve this by removing default root page in app.component.ts
and setting it when response comes from firebase.
app.component.ts
rootPage;
constructor(private afAuth: AngularFireAuth, )
{
this.afAuth.auth.onAuthStateChanged((user) => {
if (!user) {
this.rootPage = LoginPage;
} else {
this.rootPage = HomePage;
}
});
this.initializeApp();
}
Upvotes: 0
Reputation: 6900
Try this, it will return an observable which will wait for the result.
getUid() {
return this.afAuth.authState.map((auth) => {
if(auth == null) {
return false;
} else {
return auth.uid;
}
});
}
and in home.ts you can subscribe to it
constructor(private cp: CommonProvider) {
cp.getUid().subscribe(uid=>{
console.log(uid)
})
}
Upvotes: 1