Search code examples
angularfirebasefirebase-authenticationangularfire2

Angularfire2 Authentication: How to get the current user?


In my angular-app I am using angularfire2 Authentication. When opening a certain window, I want to get the email of the current user.

To this end, I wrote the following code:

ngOnInit() {

    this.currentUserEmail = this.angularFireAuth.authState
      .switchMap(user => {
          console.log("this is a test");
          return user.email;
      });

}

The code follows the documentation here: https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/#Step-3-Auth-Service

However, for some reason, the part after "switchMap" is never entered". So the line "this is a test" gets never printed.

How can I get the current user (and his/her email)?


Solution

  • This should work fine.

    constructor(public afAuth: AngularFireAuth){}
    
    this.afAuth.auth.onAuthStateChanged(user => {
          if (user) {
            // logged in or user exists
          }
          else {
            // not logged in
          }
    })
    

    Note: At above, It will trigger every time when auth state have changed (sign-in, sign-out)

    Another way to get user:

    this.afAuth.authState.subscribe(user => {
       if (user){
    
       }
       else{
    
       }    
    })
    

    You also can get another user data. For the email you can call 'user.email' get email