Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularFire2 Get Authenticated User ID in Typescript

I'm trying to work out how I can get the uid of the Firebase Authenticated user within TypeScipt:

<div> {{ (user | async)?.uid }} </div>

I have the following TS code:

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app'

@Component({
  selector: 'app-user-portal',
  templateUrl: './user-portal.component.html',
  styleUrls: ['./user-portal.component.css']
})
export class UserPortalComponent implements OnInit {
  user: Observable<firebase.User>;

  constructor(
              public afAuth: AngularFireAuth
  ) {
    this.user = afAuth.authState;
  }

  ngOnInit() {

  }
}

Everything I've read suggests I need to access the id property of...

this.afAuth.auth.currentUser.uid

... but this doesn't seem exposed. If I change that to...

this.afAuth.auth.currentUser.toJSON()

... and send that to the console, then indeed I see a uid property. How can I get that property?

Is this even the correct way to obtain a the uid for the user? Would...

this.afAuth.auth.currentUser.getIdToken()

... be better? If this is better, I cannot see how to get the uid out of this either. Suggestions?

like image 662
flipcode Avatar asked Oct 18 '22 06:10

flipcode


1 Answers

You can get the uid from idToken Observable

this.afAuth.idToken.subscribe(user => {
            this.user = user;
            this.lists = this.af.list(`/lists/${user.uid}`);
        });

Keep in mind that this is an observable, meaning that you can create a chain using this as a base with mergeMap, map, etc.

like image 102
Supamiu Avatar answered Oct 29 '22 19:10

Supamiu