To the few Angulars developers on this forum. I hope the title is self explanatory, but to give you some context, this is what’s going on.
I am basically trying to implement a logic that when the user is logged in, they should be taken immediately to the home page and skip the login page. Right now my code works, but there’s a delay, because the value of my BehaviorSubject
is initialized as false
and when I subscribe to it in my app.component.ts the initialization value of my BehaviorSubject
is always false
, then it changes to the last emitted value.
My problem is that due to the small delay, the login page first appears on the screen then it quickly changes to the home page.
Look at this screenshot:
TL;DR What can I do so when I subscribe to my BehaviorSubject
I always get the last emitted value, ignoring its initial value?
Below some code for more info:
service.ts:
authenticationState = new BehaviorSubject(false);
login() {
return this.storage.set(TOKEN_KEY, "user123").then(() => {
this.authenticationState.next(true);
});
}
app.component.ts:
constructor(...) { this.initializeApp() }
initializeApp() {
console.log(
"auth state current value is: " +
this.authService.authenticationState.getValue()
);
this.authService.authenticationState.subscribe(state => {
console.log("Auth state: " + state);
if (state) {
this.router.navigate(["home"]);
} else {
this.router.navigate(["login"]);
}
});
}