问题
How do I grab the logged in user?
I am doing this: console.log('Logging in...'); this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password);
But the docs are not clear on how to get the user in code. They show a way in the template but I need to store the current user.
回答1:
To get current user:
let user = AngularFireAuth.auth.currentUser;
// returns user object
For some reason each page refresh causes currentUser to disappear and I store user id (UID) in local storage, so I am able to remember the user and reference to Firestore later:
localStorage.setItem('userUID', user.uid);
// ...
let userID = localStorage.getItem('userUID');
AngularFirestore.firestore.collection('users')
.doc(userID)
// ...
On logout you simply logout user and remove local storage value:
logout() {
AngularFireAuth.auth.signOut().then(() => {
localStorage.removeItem('userUID');
};
}
回答2:
AngularFireAuth.authState is an Observable, so you can subscribe on it, and then get user instance :
private user: firebase.User;
constructor(public afAuth: AngularFireAuth) {
afAuth.authState.subscribe(user => {
this.user = user;
});
}
回答3:
I figured it out!
console.log('Logging in...');
this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password).then((user) => {
this.user = this.afAuth.authState;
});
来源:https://stackoverflow.com/questions/46748714/grabbing-the-current-user-in-angularfireauth