Grabbing the current user in AngularFireAuth

情到浓时终转凉″ 提交于 2020-01-04 07:36:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!