0
votes

I am using simple email/password and google signin (firebase) login authentication in my Angular project. I want to retrieve User Id (UID) of the user who is currently logged in the product. Is there a way angular provides to retrieve the UID?

Firebase Authentication data

this.authenticationService.SignUp(this.institutes.email,"123456");
    console.log(this.af.auth.currentUser.uid);
Authentication Script:

SignUp(email: string, password: string) {
this.angularFireAuth
.auth
.createUserWithEmailAndPassword(email, password)
.then(res => {
console.log('You are Successfully signed up!', res);
this.angularFireAuth
    .auth
    .signInWithEmailAndPassword(email, password)
    .then(res => {
    console.log('You are Successfully logged in!');
    return 1;
    })
    .catch(err => {
    console.log('Something is wrong:',err.message);
    });
})
.catch(error => {
console.log('Something is wrong:', error.message);
});
}

I have signed up a new account and logged in the user at the same time. I tried to retreive UID of the user after logging in, but I am receiving the folloing error: Error:Object is possibly 'null'. Error is on line: console.log(this.af.auth.currentUser.uid);

2

2 Answers

2
votes

To retrieve the uid, you can use AngularFire and do the following:

export class AppComponent {
  constructor(public afAuth: AngularFireAuth) {
  }
  getUid() {
    this.afAuth.auth.currentUser.uid;
  }
}

You can check here for more information:

https://github.com/angular/angularfire/blob/master/docs/auth/getting-started.md

2
votes

Peter answered how to get the UID of the logged-in user when you use AngularFire2. If you're not using AngularFire (or even if you are), you can get the UID of the current user with:

firebase.auth().currentUser.uid