Ad

How To Get Current Users "uid" In Component | Angular 7

Trying to make that each user can create and read his own data. I am working everything same as in this tutorial but its not working as there: https://angularfirebase.com/lessons/managing-firebase-user-relationships-to-database-records/

My database is structured like this:

 -|items
     -|userId
         -|itemId

This is my service:

  userId: string;

  constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) {
    this.afAuth.authState.subscribe(user => {
      if(user) this.userId = user.uid
    })
  }

And example function in service that gets items from database:

getRelays(): Observable<any[]> {
    if(!this.userId) return;
    this.relaysRef = this.db.list('relays/' + this.userId)
    return this.relaysRef.snapshotChanges().pipe(
      map(changes => 
        changes.map(c => ({ $key: c.payload.key, ...c.payload.val() }))
      )
    );
  }

I want to access that current users id in component so I can get items based on current user but variable userId only works inside subscription and returns undefined outside it.

This is how i login and logout (in another component):

login() {
  this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
}

logout() {
  this.afAuth.auth.signOut();
}

Thanks for help!

Ad

Answer

It's because observables are asynchronus. Since the details of the user are brought in an asynchronous manner. The userId will not be available outside the subscribe method. So you need to write the logic inside the subscribe block inorder to achieve the desired result.

this.afAuth.authState.subscribe(user => {
      if(user) this.userId = user.uid
      //you have to write the logic here.

    }) 
Ad
source: stackoverflow.com
Ad