Angular 结合ngxs和rxjs创建路由保护
因为我对RXJS和NGXS还不太熟悉,所以请跟我谈谈。我正在尝试使用这两个库设置authguard 因此,首先: /AuthState.tsAngular 结合ngxs和rxjs创建路由保护,angular,ngxs,Angular,Ngxs,因为我对RXJS和NGXS还不太熟悉,所以请跟我谈谈。我正在尝试使用这两个库设置authguard 因此,首先: /AuthState.ts @Injectable() export class AuthState { @Selector() static isAuthenticated(state: AuthStateModel): boolean { return !!state.token; } @Action(Login) login(ctx: State
@Injectable()
export class AuthState {
@Selector()
static isAuthenticated(state: AuthStateModel): boolean {
return !!state.token;
}
@Action(Login)
login(ctx: StateContext<AuthStateModel>, action: Login) {
return this.authService.login(action.payload).pipe(
tap((result: { token: string }) => {
ctx.patchState({
token: result.token,
username: action.payload.username
});
})
);
}
// ... left out for brevity
canActivate(_, state: RouterStateSnapshot) {
// I'd like to do an early return when the user is not authenticated
// And I was assuming since the `isAuthenticated` method in AuthState returns a boolean this would work... (but it doesn't)
if (!this.store.selectOnce((authState) => authState.isAuthenticated)) {
this.router.navigate(
['auth/login'],
{ queryParams: { returnUrl: state.url } }
);
return false;
}
// otherwise all is good...
return true;
}
但这是行不通的。所以我可能弄错了其中一个概念。好的。我有点倒退:
canActivate(_, state: RouterStateSnapshot) {
const isAuthenticated = this.store.selectSnapshot(AuthState.isAuthenticated);
if (!isAuthenticated) {
this.router.navigate(['auth/login'], { queryParams: { returnUrl: state.url } });
return false;
}
return true;
}
事实证明,您应该使用selectSnapshot从类AuthState中获取属性isAuthenticated。(很明显)
另见