Best way to re-initialize your own NgModule providers?

Not sure I can claim it’s a “best practice”, but I have found life in Angular-land much more natural once I made an attempt to do things in a reactive manner (as opposed to imperative), and managing user authentication state is probably the poster child for this for me.

So you have an authentication state service (or bolt this functionality onto some other natural service that already exists).

authNotifier: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);

You can replace boolean with some sort of credential object if that’s important to you. I have generally found that in most situations, all I care about is “authenticated or not?”. Login/logout is as simple as injecting this service and calling next(true) or next(false) on authNotifier. The reason for a stack depth of 1 is that we only want to know about the most recent authentication state, not history.

Now in your other providers, you can do this:

constructor(auth: AuthService) {
  auth.authNotifier.subscribe((authed) => {
    if (authed) {
      this.goGetStuff();
    } else {
      this.burnEverythingDown();
    }
}

…and in your app component, similarly:

constructor(auth: AuthService) {
  auth.authNotifier.subscribe((authed) => {
    if (authed) {
      this.rootPage = DashboardPage;
    } else {
      this.rootPage = LoginPage;
    }
}