Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 305
Jonathan Lightbringer Avatar asked May 26 '18 11:05

Jonathan Lightbringer


People also ask

What is NGXS store?

NGXS. Store. The store is a global state manager that dispatches actions your state containers listen to and provides a way to select data slices out from the global state.

Should we unsubscribe from NGXS selector?

Yes, if you subscribe manually in the component then you need to unsubscribe. Best to avoid that if possible and subscribe in the component template using the async pipe.


1 Answers

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

like image 103
Mark Whitfeld Avatar answered Sep 19 '22 09:09

Mark Whitfeld