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

Angular 6 路由配置问题:未登录用户无法访问注册页

解决Angular未登录拦截与注册页放行问题

问题分析

当前未配置路由权限控制逻辑,导致所有页面(包括注册页)都被拦截跳转到登录页。需要通过**路由守卫(AuthGuard)**实现权限区分:允许未登录用户直接访问登录页和注册页,拦截其他所有未登录请求并跳转至登录页。


1. 创建认证守卫(AuthGuard)

生成一个实现CanActivate接口的守卫服务,用于判断用户登录状态并控制路由访问权限:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service'; // 需自行实现登录状态管理服务

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    // 用户已登录,放行
    if (this.authService.isLoggedIn()) {
      return true;
    }

    // 允许未登录用户直接访问登录、注册页
    const allowedPublicPaths = ['/pages/login', '/pages/register'];
    if (allowedPublicPaths.includes(state.url)) {
      return true;
    }

    // 未登录且访问非公开页面,跳转至登录页
    this.router.navigate(['/pages/login']);
    return false;
  }
}

补充:AuthService示例实现(用于判断登录状态)

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  // 假设登录后将token存储在localStorage中
  isLoggedIn(): boolean {
    return !!localStorage.getItem('authToken');
  }
}

2. 修改路由配置,应用守卫

修改app-routing.ts

给需要登录才能访问的核心路由(FullLayoutComponent下的子路由)添加守卫,同时处理根路径重定向和404页面:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {FullLayoutComponent} from './layouts/full-layout.component';
import {SimpleLayoutComponent} from './layouts/simple-layout.component';
import { AuthGuard } from './auth.guard'; // 导入守卫

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full',
  },
  {
    path: '',
    component: FullLayoutComponent,
    data: { title: 'Home' },
    canActivate: [AuthGuard], // 给核心路由添加守卫,子路由自动继承权限控制
    children: [
      {
        path: 'home',
        loadChildren: './layouts/home/home.module#HomeModule'
      },
      {
        path: 'cns',
        loadChildren: './components/cns/cns.module#CnsModule'
      },
    ]
  },
  {
    path: 'pages',
    component: SimpleLayoutComponent,
    data: { title: 'Pages' },
    children: [
      {
        path: '',
        loadChildren: './pages/pages.module#PagesModule',
      }
    ]
  },
  // 处理未匹配的路由
  {
    path: '**',
    redirectTo: '/pages/404'
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

修改pages-module-routing.ts

给非公开页面(如404、500)按需添加守卫,登录和注册页不添加守卫,允许直接访问:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {P404Component} from './404.component';
import {P500Component} from './500.component';
import {LoginComponent} from './login/login.component';
import {RegisterComponent} from './register.component';
import { AuthGuard } from '../auth.guard'; // 可选,给404/500添加守卫

const routes: Routes = [
  {
    path: '',
    data: { title: 'Example Pages' },
    children: [
      {
        path: '404',
        component: P404Component,
        data: { title: 'Page 404' },
        canActivate: [AuthGuard] // 可选,若404需登录查看则添加,否则移除
      },
      {
        path: '500',
        component: P500Component,
        data: { title: 'Page 500' },
        canActivate: [AuthGuard] // 可选
      },
      {
        path: 'login',
        component: LoginComponent,
        data: { title: 'Login Page' }
        // 不添加守卫,允许未登录访问
      },
      {
        path: 'register',
        component: RegisterComponent,
        data: { title: 'Register Page' }
        // 不添加守卫,允许未登录访问
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class PagesRoutingModule {}

3. 验证效果

  • 未登录状态下访问localhost:4200、localhost:4200/home等核心页面,会自动跳转到登录页
  • 未登录状态下访问localhost:4200/pages/register、localhost:4200/pages/login,可直接进入对应页面
  • 登录后可正常访问所有页面

内容的提问来源于stack exchange,提问作者Cássia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:40:11