如何使用selectSnapshot?解决AuthenticationState无token属性报错
解决“Property 'token' does not exist on type 'AuthenticationState'”报错问题
我来帮你搞定这个TypeScript报错问题!先拆解下问题根源:
你在守卫里把store.selectSnapshot的state类型标注成了AuthenticationState,但这个类是用来定义NgRx选择器的,它本身并没有token属性——真正存储token数据的是AuthenticationStateModel这个状态模型类。TypeScript的类型检查机制严格,自然会提示找不到token属性。
给你两个解决方案,第二个更符合NgRx的最佳实践:
方案1:修正类型标注
直接把selectSnapshot里的state类型改成实际的状态模型AuthenticationStateModel:
canActivate(): boolean { const token = this.store.selectSnapshot((state: AuthenticationStateModel) => state.token); if (!token) { return true; } this.router.navigate(['home']); return false; }
方案2:复用已定义的Selector(推荐)
既然你已经在AuthenticationState里写好了静态的token选择器,直接调用它更规范,还能自动推导正确类型,不用手动编写箭头函数:
canActivate(): boolean { const token = this.store.selectSnapshot(AuthenticationState.token); if (!token) { return true; } this.router.navigate(['home']); return false; }
总结下核心逻辑:别把选择器类和状态模型搞混啦,selectSnapshot拿到的是状态模型的实例,不是选择器类的实例~
内容的提问来源于stack exchange,提问作者Jonathan Lightbringer
相关产品推荐
相关产品推荐

