Ngxs - 如何使用selectSnapshot?

Jon*_*ger 7 store angular ngxs

我有一个警卫,检查状态是否有令牌.

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

  this.router.navigate(['home']);
  return false;
}
Run Code Online (Sandbox Code Playgroud)

然后我有这样的事情:

export class AuthenticationState {
  @Selector()
  static token(state: AuthenticationStateModel) {
    return state.token;
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误.'AuthenticationState'类型上不存在属性'token'

Mar*_*eld 11

你在这里犯的错误是你假设lambda的state参数AuthenticationState实际上是你的整个应用程序状态,它是一个父类AuthenticationState.您应该像这样传递您的选择器:

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

  this.router.navigate(['home']);
  return false;
}
Run Code Online (Sandbox Code Playgroud)

有实际上是一个通过后的NGXS笔者前几天在这个确切的话题: https://medium.com/@amcdnl/authentication-in-ngxs-6f25c52fd385