Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to constructor of canActivate?

I have the following route path:

{
    path: 'teacher',
    component: DashboardTeacher, canActivate: [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?

like image 523
OPV Avatar asked May 31 '18 12:05

OPV


2 Answers

Your route should be configured like:

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

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
    }
}
like image 98
Sundar Singh Avatar answered Nov 17 '22 20:11

Sundar Singh


try this way:

{
    path: 'teacher',
    component: DashboardTeacher, canActivate: [AccessGuardTeacher],
    data: {type: ['Teacher']}
}

export class AccessGuardTeacher implements CanActivate {

  constructor(private role: string) {
  }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    let type = route.data["type"] as Array<string>;

  }
}
like image 34
Mitesh Avatar answered Nov 17 '22 20:11

Mitesh