Ngxs - 如何使用selectSnapshot?

时间:2018-05-26 11:52:01

标签: angular store ngxs

我有一名警卫,检查状态是否有令牌。

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

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

然后我有这样的事情:

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

我收到错误。 “AuthenticationState”类型上不存在属性“token”

1 个答案:

答案 0 :(得分:7)

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

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

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

几天前,NGXS的作者确实发了一篇关于这个话题的帖子: https://medium.com/@amcdnl/authentication-in-ngxs-6f25c52fd385