我正在使用 Angular,这是为了我的身份验证检查:
export class EnsureAuthenticated implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (localStorage.getItem('token')) {
return true;
}
else {
this.router.navigateByUrl('/login');
return false;
}
}
}
{
path: 'path',
component: myComponent,
canActivate: [EnsureAuthenticated]
}
它工作正常,但我的问题是用户和管理员都可以访问此页面。
我知道我没有对此设定任何条件。如何为其设置适当的条件?
我不想以管理员身份访问此页面
最佳答案
请参阅 stackblitz 中的此示例
在你的app-routing.module.ts中
const routes: Routes = [
{
path: "admin",
component: AdminOnlyComponent,
canActivate: [RoleGuardService],
data: { roles: ['admin']}
},
...
}
在您的 RoleGuardService 中
import { Injectable } from '@angular/core';
import { UserRolesService} from './user-roles.service';
import { Router, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class RoleGuardService {
constructor(private getUserRoles: UserRolesService) { }
canActivate(route: ActivatedRouteSnapshot): boolean {
return route.data.roles.some( ai => this.getUserRoles.getRoles().includes(ai) );
}
}
在 UserRolesService 中
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserRolesService {
userRoles: string[] = [];
constructor() { }
setRoles(Roles: string[]){
this.userRoles = Roles.slice(0);
}
getRoles(){
return this.userRoles;
}
}
当用户登录系统时设置 Angular 色或从本地存储获取这些 Angular 色......
关于基于角色的 Angular 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536856/