Ghadir
Ghadir

Reputation: 547

Angular + Firebase auth: how to access the user information from any component

I have a component (actually, the app component) that calls a firebase anonymous sign in function on ngAfterContentInit:

  ngAfterContentInit(){
    firebase.auth().signInAnonymously()
  .then(() => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('the uid of the anonymous user is '+ user.uid);
        // User is signed in
      } else {
        // User is signed out
      }
    });
    // Signed in..
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  });
  }

It is working, and the uid of the anonymous user is getting printed.

However, now I need to access this uid from another component. I haven't set up an auth.service.ts file or anything, just using the above function.

How would I go about this? I am new to Angular (coming from ReactJS), and in ReactJS I would have put the user information inside the Redux State. Is there something similar in Angular? [I am already using the required modules to connect Angular to Firebase Auth].

Alternatively, is there an easy way to access the signed-in user information without having to deal with state management in the first place?

Many thanks for any help provided.

Upvotes: 0

Views: 609

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7398

The simplest way to do it is when you use the onAuthStateChanged listener to route your users to pages they only can see as authenticated users. In that case you can get the current user with the currentUser form firebase auth like this:

const user = firebase.auth().currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/firebase.User
  // ...
} else {
  // No user is signed in.
}

Make sure that you are on a page that is only visible when authenticated and check for null valuein user.

Upvotes: 1

Related Questions