0

When is the firebase user persistence loaded? I have some APIs I need to hit using data stored in the Firebase persistence. These APIs run in the constructor of the page. As such it appears that firebase.currentuser is null until after these APIs are hit. This is causing issues with my backend code.

Is there a way to force angular firebase to load the current user sooner?

here is an example

constructor(public environmentService : EnvironmentService)
{
   firebase.initializeApp(config, "Test");
   this.getUser() //returns null here
}

getUser()
{
   return firebase.app("Test").currentUser 
}

laterAPIcall () //called about 1 second later after constructors finish
{
   this.getUser() // returns the current user which is not null anymore
}

EDIT: I need some way to force firebase to load the current user during or before the constructor of services runs. Is this possible?

Mindstormer
  • 299
  • 3
  • 16

1 Answers1

1

You're supposed to use an auth state observer to get a callback when the current user is first known after a page is loaded. It's the best way to react as soon as possible so that you can render the page with user info.

this.afAuth.authState.subscribe(res => {
  if (res && res.uid) {
    console.log('user is logged in');
  } else {
    console.log('user not logged in');
  }
});

See also:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Sadly this will not work either due to the on auth state changed observable happening after construction. I need some way to force firebase to load the current user during or before the constructor of services runs. – Mindstormer Aug 26 '20 at 17:17
  • You don't really have another option, other than the poll currentUser periodically until it changes. I suggest building your app around the reactive native of this callback rather than trying to wedge something else in. – Doug Stevenson Aug 26 '20 at 17:25