在我的 Angular8 应用程序中,有 2 个用于用户和管理员的仪表板页面,我想通过使用 PanelComponent 的用户 Angular 色来加载相应的仪表板。我想在PanelComponent.html中使用ngIf
并根据 Angular 色加载相应的仪表板,但不确定这是否是个好主意:(
另一方面,也有一些相关问题,例如 How to achieve Role Based redirection after login in Angular-5? ,但是没有一个很好的例子。那么,实现这种方法的最佳方法是什么?
最佳答案
Angular Route Guards 是支持基于 Angular 色的访问的最佳实践。 但是,如果您只想支持两个页面的基于 Angular 色的访问,并且需求不会及时扩展,那么我认为使用 ngIf 没有任何问题。在这种情况下我会走那条路。
如果你想使用路由保护,那么你应该相应地实现 CanActivate 接口(interface)。这将是您的路线守卫实现。此类负责根据 Angular 色显示或不显示所请求的页面。如果用户没有所需的 Angular 色,则会重定向到您创建的 http 404 或 403 页面。
import { Injectable } from '@angular/core';
import {
Router,
CanActivate,
ActivatedRouteSnapshot
} from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class RouteGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {
}
canActivate(route: ActivatedRouteSnapshot): boolean {
if (
!this.auth.isAuthorized(route.data.roleCode)
) {
this.router.navigate(NotFoundPage.PATH);
return false;
}
return true;
}
}
您可以在 app-routing.module 中设置路由的 Angular 色组,如下所示
export const ROUTES: Routes = [
{
path: 'admin',
component: AdminDashBoardComponent,
canActivate: [RouteGuardService],
data: {
roleCode: 'admin'
}
},
{
path: 'user',
component: UserDashBoardComponent,
canActivate: [RouteGuardService],
data: {
roleCode: 'user'
}
},
{
path: 'other',
component: OtherPageComponent,
canActivate: [RouteGuardService],
data: {
roleCode: 'user'
}
},
{ path: '**', redirectTo: '' }
];
为了简洁起见,我没有分享身份验证服务,它所能做的只是比较用户的 Angular 色代码和route.data.roleCode。 您还可以将身份验证逻辑集成到此 RouteGuardService 中,如果用户未登录,您可以将其再次重定向到登录页面。
所有这些都是为了防止未经授权访问您的页面。
您对登录后重定向到正确页面的要求听起来像是您想要一个动态主页。登录后根据 Angular 色组进行重定向并不是一个好的做法。
您可以在主页组件的 ngOnInit 中进行重定向。这提供了更好的设计。
export class HomePageComponent {
...
ngOnInit() {
if (this.auth.isAuthorized('admin')) {
this.router.navigateByUrl('/admin');
} else if (this.auth.isAuthorized('user')) {
this.router.navigateByUrl('/user');
}
}
关于angular - Angular 6+ 中基于角色的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57356145/