Search code examples
angularreduxrxjsrxjs6ngoninit

Select a State with RxJS in Angular 6 doesn't work


In a web app I'm using Angular and RxJS 6. The application has a login, the response of the login is a token so, after the login, I save the token in the sessionStorage and then I decode the token to save the current logged in user. This is the state after the login:

enter image description here

I'm trying to develop this behaviour: if the user go to page "..login" (so in login.components.ts) and if he is already logged in, the application will redirect to the home page. This is my code inside ngOnInit() in login.component.ts:

  ngOnInit() {
   this.store.select('auth')
     .pipe(take(1),
       map((authState: fromAuth.State) => {
         console.log('test');
         if (authState.authenticated) {
           this.router.navigate(['/home']);
         }
      }));
}

This is the Interface of AppState:

export interface AppState {
  user: fromProfile.State,
  auth: fromAuth.State,
  core: fromCore.State
}

Testing it, I login, I go to home, then I go to login page, I put a breakpoint in the console.log() but it doesn't reach the breakpoint, it doesn't even enter it, and so it doesn't redirect to home page. Why?

* UPDATED *: this is the screen of debug enter image description here


Solution

  • The select() function returns an Observable so you have to .subscribe() to it in order the pipe to be called.