Search code examples
firebasefirebase-authenticationangularfire2google-cloud-firestore

Grabbing the current user in AngularFireAuth


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.


Solution

  • 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');
       };
    }