Search code examples
angularstorengxs

How to use selectSnapshot?


I have a guard that checks if there is a token on state.

canActivate(): boolean {
const token = this.store.selectSnapshot((state: AuthenticationState) => state.token);
  if (!token) {
    return true;
  }

  this.router.navigate(['home']);
  return false;
}

Then I have something like this:

export class AuthenticationState {
  @Selector()
  static token(state: AuthenticationStateModel) {
    return state.token;
  }
}

I get an error. Property 'token' does not exist on type 'AuthenticationState'


Solution

  • The mistake you are making here is that you are assuming that the state parameter of the lambda would be your AuthenticationState it would in fact be the entire application state, which is a parent of the AuthenticationState. You should rather pass your selector like this:

    canActivate(): boolean {
    const token = this.store.selectSnapshot(AuthenticationState.token);
      if (!token) {
        return true;
      }
    
      this.router.navigate(['home']);
      return false;
    }
    

    There was actually a post by the author of NGXS a few days ago on this exact topic: https://medium.com/@amcdnl/authentication-in-ngxs-6f25c52fd385