Grabbing the current user in AngularFireAuth
Asked Answered
B

4

6

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.

Buyers answered 14/10, 2017 at 19:50 Comment(0)
H
3

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');
   };
}
Hayley answered 27/12, 2017 at 20:31 Comment(1)
The currentUser disappears because the user has not arrived, yet. You should use a JavaScript Promise.Evolutionary
Z
8

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;
    });
  }
Zabrina answered 18/12, 2018 at 8:28 Comment(0)
H
3

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');
   };
}
Hayley answered 27/12, 2017 at 20:31 Comment(1)
The currentUser disappears because the user has not arrived, yet. You should use a JavaScript Promise.Evolutionary
B
0

I figured it out!

console.log('Logging in...');
this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password).then((user) => {
  this.user = this.afAuth.authState;
});
Buyers answered 14/10, 2017 at 20:3 Comment(0)
S
0

Solution I founded online, and it works no matter page refreshes:

AngularFireAuth.authState.pipe(first()).toPromise();

https://fireship.io/snippets/check-if-current-user-exists-with-angularfire/

Sutton answered 28/2, 2021 at 22:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.