本文介绍了如何将参数传递给canActivate的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下路线路径:

{
    path: 'teacher',
    component: DashboardTeacher, canActivate: [AccessGuardTeacher('Teacher')]
}

如您所见,我尝试在 AccessGuardTeacher 类中传递参数Teacher":

As you can see I tried to pass parameter 'Teacher' in class AccessGuardTeacher:

export class AccessGuardTeacher implements CanActivate {

  constructor(private role: string) {
  }
}

如何正确地做到这一点?

How to do that right?

推荐答案

你的路由应该这样配置:

Your route should be configured like:

{
   path: 'teacher',
   component: DashboardTeacherComponent,
   canActivate: [AccessGuardTeacher],
   data: {
            role: 'teacher'
         }
}

在您的 CanActivate Guard 中获取您的路线数据

Get your route data in your CanActivate Guard

export class AccessGuardTeacher implements CanActivate {

     constructor() {
     }

    canActivate(route: ActivatedRouteSnapshot): boolean {

        const role = route.data.role;
        return true; //based on your condition
    }
}

这篇关于如何将参数传递给canActivate的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-22 01:55