11

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'

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Jonathan Lightbringer
  • 435
  • 2
  • 12
  • 27

1 Answers1

15

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

Mark Whitfeld
  • 6,500
  • 4
  • 36
  • 32
  • Is it possible that the `AuthenticationState.token` selector could get state which is undefined. Should you account for undefined state in the selector function? – O.MeeKoh Feb 12 '20 at 01:27