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

基于NgRx Store的Angular函数式路由守卫示例请求

函数式CanActivate守卫访问NgRx Store示例

下面是可直接复用的函数式路由守卫示例,用于通过NgRx Store检查用户认证状态:

1. 定义守卫函数

import { CanActivateFn, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { selectIsAuthenticated } from './path-to-your-auth-selectors';
import { map } from 'rxjs/operators';
import { inject } from '@angular/core';

export const authGuard: CanActivateFn = (route, state) => {
  // 函数式守卫中用inject获取依赖,替代类守卫的构造注入方式
  const store = inject(Store);
  const router = inject(Router);

  // 订阅Store中的认证状态
  return store.select(selectIsAuthenticated).pipe(
    map(isAuthenticated => {
      if (isAuthenticated) {
        // 已认证,允许进入目标路由
        return true;
      }
      // 未认证,跳转到登录页并携带当前路由地址,方便登录后跳转回来
      return router.createUrlTree(['/login'], { 
        queryParams: { returnUrl: state.url } 
      });
    })
  );
};

2. 在路由配置中使用

将守卫添加到需要保护的路由上:

import { Routes } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { authGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [authGuard]
  }
];

3. 进阶:处理异步状态加载

如果需要先确保用户状态从服务器加载完成再判断权限,可以扩展守卫逻辑:

import { CanActivateFn, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { selectUser, selectUserLoaded } from './path-to-your-user-selectors';
import { loadUser } from './path-to-your-user-actions';
import { map, switchMap, filter } from 'rxjs/operators';
import { inject } from '@angular/core';
import { of } from 'rxjs';

export const authGuard: CanActivateFn = (route, state) => {
  const store = inject(Store);
  const router = inject(Router);

  return store.select(selectUser).pipe(
    switchMap(user => {
      if (!user) {
        // 用户信息未加载,触发加载动作
        store.dispatch(loadUser());
        // 等待加载完成后再获取认证状态
        return store.select(selectUserLoaded).pipe(
          filter(loaded => loaded),
          switchMap(() => store.select(selectIsAuthenticated))
        );
      }
      // 用户信息已存在,直接返回认证状态
      return of(user.isAuthenticated);
    }),
    map(isAuthenticated => isAuthenticated ? true : router.createUrlTree(['/login']))
  );
};

关键说明

  • 函数式守卫中使用inject()替代类守卫的构造函数注入,获取NgRx Store和Router实例
  • 通过store.select()订阅指定的selector,获取Store中的状态
  • 必须返回Observable<boolean | UrlTree>,Angular会自动处理订阅和资源清理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:06:02