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

Angular 20项目中未认证守卫(unauthGuard)在用户已登录时未拦截/auth路由的问题求助

Angular 20项目中未认证守卫(unauthGuard)在用户已登录时未拦截/auth路由的问题求助

我正在开发一个Angular 20的项目,写了一个未认证守卫unauthGuard,原本期望的逻辑是:当用户未登录(freelancer状态为null)时可以正常访问/auth开头的路由;当用户已登录(freelancer状态不为null)时,访问/auth路由会被自动重定向到首页/。

目前的问题是:未登录状态下功能完全正常,能自由访问/auth下的所有子路由;但登录后,我仍然可以直接输入/auth/*的路径访问对应页面,完全没有被守卫拦截,这和预期不符。

以下是我的相关代码文件,麻烦帮忙看看哪里出了问题:

1. 未认证守卫代码 unauth-guard.ts

import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { map } from 'rxjs';
import { AppState } from '../../../shared/store/app.state';
import { selectFreelancer } from '../../../shared/store/freelancer/freelancer.selectors';

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

  return store.select(selectFreelancer).pipe(
    map((freelancer) => {
      if (freelancer === null) {
        return true;
      }
      router.navigate(['/']);
      return false;
    }),
  );
};

2. 路由配置文件 app.routes.ts

import { Routes } from '@angular/router';
import { unauthGuard } from './core/guards/unauth/unauth-guard';

export const routes: Routes = [
  {
    path: 'auth',
    loadChildren: () => import('./modules/auth/auth-module').then((m) => m.AuthModule),
    canActivate: [unauthGuard],
  },
  {
    path: '',
    loadChildren: () => import('./modules/home/home-module').then((m) => m.HomeModule),
  },
  {
    path: '**',
    redirectTo: '/auth/login',
  },
];

3. Freelancer状态的Reducer freelancer.reducer.ts

import { createReducer, on } from '@ngrx/store';
import { FreelancerState } from './freelancer.state';
import * as FreelancerActions from './freelancer.actions';

const initialState: FreelancerState = {
  freelancer: null,
  onGetFreelancer: 'false',
};

export const freelancerReducer = createReducer(
  initialState,
  on(FreelancerActions.getFreelancer, (state) => ({
    ...state,
    onGetFreelancer: 'true',
  })),
  on(FreelancerActions.getFreelancerSuccess, (state, { freelancer }) => ({
    ...state,
    freelancer,
    onGetFreelancer: 'success',
  })),
  on(FreelancerActions.getFreelancerError, (state) => ({
    ...state,
    freelancer: null,
    onGetFreelancer: 'error',
  })),
  on(FreelancerActions.logoutFreelancer, (state) => ({
    ...state,
    freelancer: null,
    onGetFreelancer: 'false',
  })),
);

我已经把守卫绑定到了auth路由的canActivate数组中,但登录后还是能绕过守卫访问/auth下的页面。请问我该如何修改,才能让已登录用户完全无法访问/auth/*的所有路由?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 07:43:05