my *_*est 2 angular2-routing angular
我正在使用 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]
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我的问题是用户和管理员都可以访问此页面。
我知道我没有设置任何条件。如何在其上设置适当的条件?
我不想让管理员访问此页面
在stackblitz 中查看此示例
在你的 app-routing.module.ts
const routes: Routes = [
{
path: "admin",
component: AdminOnlyComponent,
canActivate: [RoleGuardService],
data: { roles: ['admin']}
},
...
}
Run Code Online (Sandbox Code Playgroud)
在你的 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) );
}
}
Run Code Online (Sandbox Code Playgroud)
在用户角色服务中
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在用户登录系统时设置角色或从您的本地存储中获取这些角色....
| 归档时间: |
|
| 查看次数: |
3753 次 |
| 最近记录: |