面试题答案
一键面试CanActivate应用场景
- 权限控制:在企业级应用中,不同角色的用户拥有不同的权限。例如,只有管理员角色的用户才能访问系统设置相关的路由,普通用户访问该路由时会被阻止。
- 登录状态判断:确保用户在访问某些受保护页面(如个人资料页、订单详情页等)之前已经登录。如果未登录,将用户重定向到登录页面。
创建和使用CanActivate保护特定路由(以登录状态判断为例)
- 创建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
方法会在每次尝试激活特定路由时被调用。这里通过调用AuthService
的isLoggedIn
方法来判断用户是否已登录,如果已登录则返回true
允许访问路由,否则返回false
并将用户重定向到登录页面。
- 配置路由使用守卫:
在
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]
,这意味着只有当AuthGuardService
的canActivate
方法返回true
时,才能激活profile
路由并显示ProfileComponent
组件。如果返回false
,则会按照守卫中的逻辑进行重定向。
CanDeactivate应用场景
- 表单未保存提示:当用户在填写表单过程中尝试离开当前页面时,使用
CanDeactivate
守卫来提示用户是否保存表单数据,避免数据丢失。 - 任务进行中阻止离开:在某些任务执行过程中(如文件上传等),阻止用户离开当前页面,确保任务顺利完成。