// auth.guard.ts
export class AuthGuard implements CanActivate {
constructor(private store: Store<fromAuth.AuthState>, private router: Router) {}
canActivate(): Observable<boolean> {
return this.store.pipe(
select(fromAuth.selectUser), // Select user from the auth state
map((user) => {
if (user) {
return true; // User is logged in, allow access to the route
} else {
this.router.navigate(['/login']); // User is not logged in, navigate to login page
return false;
}
})
);
}
}
我正在使用 ngrx 来管理身份验证状态并在身份验证防护中使用它。 CanActivate 已弃用,我想使用 CanActivateFn 来保护从身份验证缩减程序 fromAuth 到身份验证状态的路由。
要调整现有的 AuthGuard 逻辑以使用 CanActivateFn,您需要执行以下步骤:
以下是如何重构 AuthGuard 类以使用
CanActivateFn
:
确保您拥有新功能防护实施所需的导入。
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { fromAuth } from '../path-to-auth-state'; // Adjust the path to your auth state
2.使用
authGuard
创建 CanActivateFn
函数:
export const authGuard: CanActivateFn = () => {
const store = inject(Store<fromAuth.AuthState>);
const router = inject(Router);
return store.pipe(
select(fromAuth.selectUser), // Adjust the selector to match your state
map((user) => {
if (user) {
return true; // User is logged in, allow access to the route
} else {
router.navigate(['/login']); // User is not logged in, navigate to login page
return false;
}
})
);
};
authGuard
:在路由模块中,用新的
canActivate
函数替换旧的 authGuard
防护。
import { Routes } from '@angular/router';
import { authGuard } from './path-to-auth-guard'; // Adjust the path to your auth guard
const routes: Routes = [
{
path: 'protected-route',
component: ProtectedComponent,
canActivate: [authGuard]
},
// Other routes
];
确保您的
fromAuth.selectUser
选择器和 AuthState
在您的 NgRx 设置中正确定义。
// auth.selectors.ts
import { createSelector } from '@ngrx/store';
import { AuthState } from './auth.reducer'; // Adjust the path to your auth reducer
export const selectAuthState = (state: AppState) => state.auth;
export const selectUser = createSelector(
selectAuthState,
(state: AuthState) => state.user
);