Angular AuthGuard路由守卫创建与使用

作者:技术拾光

时间:2026-06-11

浏览:101

Angular中的AuthGuard 在Angular路由守卫中,AuthGuard是使用最频繁的一种。简单来说,它就像一道门禁系统,专门用于拦截未登录或权限不足的用户,阻止他们直接访问需要认证才能进入的页面。配合路由配置一同使用后,效果非常直接。 创建AuthGuard AuthGuard本质上是

文章目录

Angular中的AuthGuard

在Angular路由守卫中,AuthGuard是使用最频繁的一种。简单来说,它就像一道门禁系统,专门用于拦截未登录或权限不足的用户,阻止他们直接访问需要认证才能进入的页面。配合路由配置一同使用后,效果非常直接。

Angular AuthGuard路由守卫创建与使用

创建AuthGuard

AuthGuard本质上是一个Angular服务,生成过程也很简单。在命令行中执行以下命令即可:

ng g guard auth

该命令会在src/app/auth.guard.ts路径下生成一个名为“auth”的守卫文件。打开后,代码大致如下:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
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): Observable | Promise | boolean | UrlTree {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

核心逻辑位于canActivate()方法中。守卫通过实现CanActivate接口来定义——该接口仅要求定义这个方法,用于决定当用户尝试访问受保护路由时应如何处理。在实现时,我们注入了两个依赖:AuthService用于判断用户登录状态,Router用于页面跳转。

整个流程非常清晰:先调用this.authService.isLoggedIn()进行检测。如果用户已登录,返回true,允许访问;否则直接跳转到/login页面,返回false,拒绝访问。这种实现方式简单直接,实用性强。

使用AuthGuard保护单个路由

有了守卫之后,还需要告诉Angular哪些路由需要被保护。具体做法是在路由配置中,将AuthGuard加入canActivate数组。示例如下:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

上述代码将AuthGuard挂载在/dashboard路由的canActivate上。效果是:用户必须登录后才能访问仪表盘页面,否则会被拦截并重定向到登录页。

以上就是Angular中AuthGuard路由守卫的完整创建和使用流程。从生成守卫文件到配置路由,每一步都很清晰,上手难度也不高。在实际项目中,可以根据需要扩展权限逻辑,例如角色判断、参数验证等,但核心思路始终保持一致。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章