You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular路由守卫中用CanActivateFn替代CanActivate实现AuthReducer状态管理

基于NgRx的CanActivateFn路由守卫实现

将原有的类式CanActivate守卫改为函数式CanActivateFn的实现如下:

// auth.guard.ts
import { CanActivateFn, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { fromAuth } from './auth.reducer';
import { map } from 'rxjs/operators';

export const authGuard: CanActivateFn = () => {
  const store = inject(Store<fromAuth.AuthState>);
  const router = inject(Router);

  return store.pipe(
    select(fromAuth.selectUser),
    map((user) => {
      if (user) {
        return true;
      } else {
        router.navigate(['/login']);
        return false;
      }
    })
  );
};

关键变更说明

  • 替换类式守卫为函数式守卫,使用CanActivateFn类型定义函数
  • 不再依赖构造函数注入,改用inject()函数直接获取Store和Router实例
  • 核心逻辑与原守卫保持一致:监听NgRx中的用户状态,根据是否存在用户判断是否允许路由访问

路由配置中的使用方式

在路由模块里,将原来的类守卫引用替换为函数名:

// app-routing.module.ts
const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [authGuard] // 使用函数式守卫
  },
  // 其他路由配置...
];

内容的提问来源于stack exchange,提问作者nerdWannabe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:22:03