I don’t really like complex interactions with the navigation system, so I avoid all of that with an AuthService
that exposes an authNotifier
property that is a ReplaySubject<boolean>
with stack depth 1. In its constructor, you could do this:
constructor(storage: Storage) {
storage.ready().then(() => storage.get('jwt'))
.then((jwt) => {
this.authNotifier.next(isValid(jwt));
});
}
In the app component, you can do this:
constructor(auth: AuthService) {
auth.authNotifier.subscribe((authed) => {
if (authed) {
this.rootPage = DashboardPage;
} else {
this.rootPage = LoginPage;
}
});
}
An additional benefit of this approach is that it makes logout dead easy: inject AuthService
from anywhere and call next(false)
on its authNotifier
. No navigation interaction needed. Wherever you are checking and noticing that the token has expired can do this as well.