Search code examples
javascriptgoogle-cloud-firestorefirebase-authenticationangularfire

Retrieving UID from angularfire


I use angularfire latest version. I look this subject, there is some solutions, but they are solving old angularfire. How can i retrieve user id from angularfire?

Note: I tried this code, but it does not work:

this.users = this.db.collection<User>('users').doc(auth.currentUser.then((e) => e?.uid)).valueChanges();

My firebaseService codes: (Using this code, it gets all of the user informations. I need to current user datas).

export class FirebaseService {
  usersCollection: AngularFirestoreCollection<User>;
  users: Observable<User[]>;

  isLoggedIn = false;
  constructor(public auth: AngularFireAuth, public db: AngularFirestore) {
    this.users = this.db.collection<User>('users').valueChanges();
  }

  async signInWithEmailandPassword(email: string, password: string) {
    await this.auth.signInWithEmailAndPassword(email, password).then((res) => {
      this.isLoggedIn = true;
      localStorage.setItem('user', JSON.stringify(res.user));
    });
  }

  async signUpWithEmailandPassword(email: string, password: string) {
    await this.auth
      .createUserWithEmailAndPassword(email, password)
      .then((res) => {
        this.isLoggedIn = true;
        localStorage.setItem('user', JSON.stringify(res.user));
        var user = res.user;
        this.db
          .collection('users')
          .doc(user?.uid)
          .set({
            email: user?.email,
            uid: user?.uid,
          })
          .catch((e) => console.log(e));
      });
  }

  logout() {
    this.auth.signOut();
    localStorage.removeItem('user');
  }

  getUsers() {
    return this.users;
  }
}

Solution

  • You need to invert the relationship, first start with an observable of the user and then map it into the valueChanges.

    auth.user.pipe(
      switchMap(user => {
        if (!user) { return EMPTY; }
        return this.db.collection<User>('users').doc(user.uid)).valueChanges()
      })
    )
    

    Keep in mind the no logged in user case, as I've done here, unless you are guarding the route.