[英]Angular 6 Role based Authentication
我的项目中有5个模块。 在基于卷的创建,更新,删除和查看访问中滚动访问这些模块。
我如何在角度6中创建UI,当用户登录到应用程序并在共享服务中设置角色时,我需要该角色。 例如,admin roll访问所有服务和员工角色只查看列表不能访问创建和删除。 我很想进入角度。
请帮我解决基于卷的身份验证中的任何代码或示例
您可以创建不同的组件并有条件地呈现组件。 考虑你的例子。 为此,我创建了2个组件1.视图组件2.创建组件。
喜欢考虑代码
<div>
<button *ngIf="usertype!=='employeee">Delete</button> <!--show delete button if user is not employee-->
<create *ngIf="usertype!=='employeee"></create> <!-- Show create component if usertype is not emplyee -->
<view [data]="data"></view> <!-- view for all type of user-->
</div>
无论你打算创建,更新,删除和查看创建按钮后的任何方式,您都可以通过编程方式启用或禁用按钮。如果这是您的需要,请按照以下步骤操作
创建具有[禁用]选项的按钮,例如,
<button text="click" [disabled]="isAuthorised">Create</button>
<button text="click" [disabled]="isAuthorised">Delete</button>
这里isAuthorised是typescript中的变量,根据用户角色将变量设为boolean(true / false)。相应地启用或禁用按钮
您可以遵循许多不同的方法,但通过使用route-guards
来限制基于特定条件的route-guards
的基本思想。
在你的情况下,你可以有路由,当route-guard
授权使用它时,懒洋洋地加载你的模块,并进一步加载相同方式的嵌套路由。
确定您的路线模块。
{
path:'/dashboard',
loadChildren: './lazy.module#LazyModule'
canActivate:[ModuleRouteGuard],
data: {
accessRoles: ['Manager','HR']
}
}
LazyModule_Routes.ts
{
path:'/board',
component: ManagerBoard
canActivate:[ChildRouteGuard],
data: {
accessRoles: ['Manager']
},
resolve: {
userRoles: 'userRolesResolver' //use this resolver service to get data inside component so to decide if user can read/write . OR you can also use activatedRoutes data
}
}
路由Gaurd.ts
@Injectable()
class ModuleRouteGuard implements CanActivate { (1)
constructor(private userService: UserService) {}; (2)
canActivate() {
console.log("OnlyLoggedInUsers");
if (this.userService.isLoggedIn()) { (3)
return true;
} else {
window.alert("You don't have permission to view this page"); (4)
return false;
}
}
}
您的应用解析器,它从服务器带来用户角色。
@Injectable()
class UserRolesResolver implements Resolve<Team> {
constructor(private backend: Backend) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any {
//return this.backend.fetchTeam(route.params.id);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.