Search code examples
javascriptangularfirebase-authenticationangularfire2angular11

Subscribing to authState changes in Angular Fire


Currently I listen to auth state changes in my ngOninit of my AppComponent:

export class AppComponent implements OnInit {

  constructor(public fireAuth: AngularFireAuth) {
  }

  ngOnInit(): void {
    this.fireAuth.authState.subscribe(user => {
      if (user) {
        //logged in logic
      } else {
        //logged out logic
    }});
  }
}

Should I use the constructor instead? Is the AppComponent not a good place to do that?


Solution

  • ngOninit is perfectly fine here. Things are initialized in the constructor if they are needed before ngOnInit. I do not think it is the case here. Do not forget to unsubscribe in onDestroy.