Angular - get BehaviorSubject last value

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"]);
        }
      });
}

@psychometry, sorry to tag you but I know you work with Angular, maybe you can throw some light here.

You can try using the skip operator on your Observable before subscribing.

http://reactivex.io/documentation/operators/skip.html

This way you skip the first emitted value.

Thanks a lot man, this was exactly what I was looking for, although I had already solved it using router guard. Which approach would you say is better?

With my original implementation I don’t have to manually navigate to “home” or “login” when logging in or logging out because the logic implemented in the root of my app handles all that.

Guards are a good idea in general because as your application grows with more routes, it provides an easy way to secure all your routes.