角度路由中基于条件的身份验证防护.(路线保护不仅仅是导航)



我正在创建一个 angular2 应用程序。

export const routes: Route[] = [
{path: '',redirectTo: "login",pathMatch: "full" }, 
{path: 'login', component: LoginComponent }, 
{path: 'dashboard', component: DashboardComponent,canActivate:[AuthGuard], children:
[
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'A', component: AComponent },
{ path: 'B', component: BComponent },
{ path: 'C', component: CComponent },
{ path: 'D', component: DComponent },
]
}];

当我使用登录组件登录到我的应用程序时,它将转到具有四个子组件的仪表板组件

  1. -一个
  2. -B
  3. -C
  4. -D

现在,我已默认将重定向到我的仪表板组件。 但是为了代替此重定向,我想根据登录类型重定向到路由 A,B,C,D,例如他是管理员、超级管理员、学生或老师。

假设

如果登录用户是"管理员",他应该重定向到 ->仪表板/A

如果登录用户是"老师",那么他应该被重定向到 ->仪表板/B

我像这样创建了身份验证

@Injectable()
export class AuthGuard implements CanActivate {
constructor(public router: Router){ }
canActivate(){
if(localStorage.getItem('userData')){
return true;
}
// this.router.navigateByUrl('/');
return false;
}
}
export class activateEmployee implements CanActivate {
constructor(){ }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
console.log(localStorage.getItem('userData'), "employee");
if(localStorage.getItem('userData') == 'superadmin'){
return true;
}
// this.router.navigateByUrl('/');
return false;
}
}
export class activateSuperAdmin implements CanActivate {
constructor(public router: Router){ }
canActivate(){
console.log(localStorage.getItem('userData'), "Superadmin");
if(localStorage.getItem('userData') == 'superadmin'){
return true;
}
return false;
}
}
export class activateAdmin implements CanActivate {
constructor(public router: Router){ }
canActivate(){
console.log(localStorage.getItem('userData'),"Admin");
if(localStorage.getItem('userData') == 'admin'){
return true;
}
return false;
}
}

PS:我的主要目标是保护路由,如果有人知道受保护路由的URL,即使他无法去那里。 或者我们可以说我想要一个服务中的多个 authGuard 之类的东西。

更新

现在我已经为路由创建了不同的类,但是我收到此错误不知道为什么? 错误是

Can't resolve all parameters for activateAdmin: (?).

而不是创建 4 个不同的路由防护,您可以在路由防护中使用 switch/if-else 来仅使用一个来重构它,如下所示

canActivate(){
let theRole = localStorage.getItem('userData');
switch(theRole){
case "admin": { 
this.router.navigate(['/dashboard/a']);
return true;
} 
case "teacher": { 
this.router.navigate(['/dashboard/b']);
return true;       
} 
case "superadmin": {
this.router.navigate(['/dashboard/c']);
return true;    
} 
case "student": { 
this.router.navigate(['/dashboard/d']);
return true;
}  
default: { 
this.router.navigate(['/login'])
return false;           
} 
}

如果有 4 个不同的路线防护装置适合您,则无需遵循代码。 最后,它仍然归结为团队的个人偏好或做法

得到了解决方案(从这里提示(

我只需要通过实现条件CanActivate来创建不同的类,以便您可以申请 像这样保护你的路由

{path: 'dashboard', component: DashboardComponent,canActivate:[AuthGuard], children:
[
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'A', component: AComponent , canActivate: [activateA]},
{ path: 'B', component: BComponent , canActivate: [activateB]},
.....

最新更新