面试题答案
一键面试- 创建路由守卫:
- 在Angular中,可以通过创建一个实现
CanActivate
接口的服务来作为路由守卫。例如:
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AdminGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { const isAdmin = this.authService.isAdmin(); if (!isAdmin) { this.router.navigate(['/home']); // 非管理员用户重定向到首页 return false; } return true; } }
- 在Angular中,可以通过创建一个实现
- 在路由配置中使用守卫:
- 在
app - routing.module.ts
文件中,将创建的路由守卫应用到需要管理员权限的路由上。例如:
const routes: Routes = [ { path: 'user - management', component: UserManagementComponent, canActivate: [AdminGuard] }, { path: 'permission - settings', component: PermissionSettingsComponent, canActivate: [AdminGuard] } ];
- 在
- 在路由守卫中获取当前用户角色信息:
- 通常可以通过一个
AuthService
来管理用户的认证和角色信息。例如:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthService { private userRole: string; constructor(private http: HttpClient) {} login(username: string, password: string): Observable<boolean> { // 实际的登录逻辑,这里简单示例 return this.http.post<any>('/api/login', { username, password }) .pipe( map(response => { if (response && response.role) { this.userRole = response.role; return true; } return false; }) ); } isAdmin(): boolean { return this.userRole === 'admin'; } }
- 在路由守卫中注入
AuthService
,通过调用isAdmin
方法获取当前用户是否为管理员角色。在上述AdminGuard
中,就是通过this.authService.isAdmin()
方法来判断当前用户是否为管理员。
- 通常可以通过一个
总结:通过创建实现CanActivate
接口的路由守卫服务,并在路由配置中使用它,同时借助AuthService
来管理和获取用户角色信息,从而确保只有管理员角色的用户能够访问特定路由。