Search code examples
typescriptfirebasefirebase-authenticationfirebaseui

firebaseui with angular determine login state on revisit


I am using firebaseUI to login using facebook. My app.components.html has two divs one to show firebaseui tag and another to show after user is logged in.

My question is when i have logged in once then how do i determine that i have already logged in? The code looks like be

constructor(private afAuth: AngularFireAuth,
            private core:CoreService) {
  }

  successCallback(data: FirebaseUISignInSuccessWithAuthResult) {
    console.log('successCallback', data);
    this.core.loggedIn = true
  }


  logout() {
    this.core.loggedIn = false
    this.afAuth.auth.signOut();
  }

  errorCallback(data: FirebaseUISignInFailure) {
    alert('Failed to login')
    this.core.loggedIn = false
    console.warn('errorCallback', data);
  }

  ngOnInit(): void {
    this.afAuth.authState.subscribe(d => {console.log('subscribed to firebase auth' + JSON.stringify(d))});
  }
}

So when i revisit the successCallback is not called as there is no login clicked.


Solution

  • When you reload the page, the user's authentication state should be restored automatically and your authState subscriber will be called:

    this.afAuth.authState.subscribe(d => {
      console.log('subscribed to firebase auth' + JSON.stringify(d))
    });