Angular 15中实现基于角色的保护可以通过路由守卫来实现。路由守卫可以检查用户是否有访问特定页面的权限,并且可以通过重定向或显示错误消息来保护该页面。为了向用户发送消息,可以使用Angular的内置通知机制。
以下是一个基于角色的路由守卫示例:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable | Promise {
const expectedRole = route.data.expectedRole;
const currentUser = this.authService.getCurrentUser();
if (!currentUser || currentUser.role !== expectedRole) {
this.router.navigate(['login'], { queryParams: { returnUrl: state.url } });
return false;
}
return true;
}
}
在这个示例中,RoleGuard
检查当前用户是否具有访问该页面的权限。如果用户未登录或角色不匹配,则导航到登录页面。为了使守卫知道特定页面需要哪种角色,需要将期望的角色存储在路由数据中:
{ path: 'admin', component: AdminComponent, canActivate: [RoleGuard], data: { expectedRole: 'admin' } },
{ path: 'user', component: UserComponent, canActivate: [RoleGuard], data: { expectedRole: 'user' } }
为了向用户发送消息,可以使用Angular的MatSnackBar
组件。以下是一个通知服务示例:
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
constructor(private snackBar: MatSnackBar) {}
show(message: string) {
this.snackBar.open(message, 'Close', {
duration: 3000,
verticalPosition: 'top'
});
}
}
现在可以在应用程序中的任何组件中注入NotificationService
并使用它来向用户显示通知:
this.notificationService.show('You do not have