MST

星途 面试题库

面试题:Angular路由守卫在路由系统中的应用场景及实现方式

请举例说明Angular路由守卫(如CanActivate、CanDeactivate等)在实际项目中的应用场景。以CanActivate为例,详细描述如何创建和使用它来保护特定路由,只有满足某些条件(比如用户已登录)才能访问该路由。
21.0万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

CanActivate应用场景

  1. 权限控制:在企业级应用中,不同角色的用户拥有不同的权限。例如,只有管理员角色的用户才能访问系统设置相关的路由,普通用户访问该路由时会被阻止。
  2. 登录状态判断:确保用户在访问某些受保护页面(如个人资料页、订单详情页等)之前已经登录。如果未登录,将用户重定向到登录页面。

创建和使用CanActivate保护特定路由(以登录状态判断为例)

  1. 创建CanActivate守卫
    • 首先创建一个新的服务,假设命名为AuthGuardService。在Angular中,可以使用命令行工具ng generate service auth-guard来快速生成服务。
    • 在生成的auth - guard.service.ts文件中编写如下代码:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';//假设存在一个用于处理登录逻辑的AuthService

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

在上述代码中,AuthGuardService实现了CanActivate接口,其canActivate方法会在每次尝试激活特定路由时被调用。这里通过调用AuthServiceisLoggedIn方法来判断用户是否已登录,如果已登录则返回true允许访问路由,否则返回false并将用户重定向到登录页面。

  1. 配置路由使用守卫: 在app - routing.module.ts文件中配置路由,使特定路由使用刚才创建的守卫:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService } from './auth - guard.service';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuardService] },
  { path: 'login', component: LoginComponent }
];

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

在上述路由配置中,profile路由添加了canActivate属性,并设置为[AuthGuardService],这意味着只有当AuthGuardServicecanActivate方法返回true时,才能激活profile路由并显示ProfileComponent组件。如果返回false,则会按照守卫中的逻辑进行重定向。

CanDeactivate应用场景

  1. 表单未保存提示:当用户在填写表单过程中尝试离开当前页面时,使用CanDeactivate守卫来提示用户是否保存表单数据,避免数据丢失。
  2. 任务进行中阻止离开:在某些任务执行过程中(如文件上传等),阻止用户离开当前页面,确保任务顺利完成。