2

i am trying to create conditional routing in angular 5 and i have seen this post and the official milestone page of angular: Angular2 conditional routing.

But i didn't find a way to create multiple conditions based on input variables. here is my code :

import { Injectable } from '@angular/core';
import {CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {AuthServiceService} from './auth-service.service';
@Injectable()
export class AuthguardService  implements CanActivate{

    constructor(
        private router: Router,
        private AuthService:AuthServiceService
    ) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if(this.AuthService.ValidAs("User")!=true){
            this.router.navigate(['pages/login']);
            return false;
        }else{
          return true;
        }
    }

}

My AuthService.ValidAs() method takes an argument to determine the type of user to try and validate as rightful to access a route and returns a boolean. i have three types of users, how do i pass extra arguments to the canActivate property in my routes in order to use that as argument to my ValidAs method.

If there is any other way to create multiple canActivate instances without multiplying files, let me know.

Kaki Master Of Time
  • 1,428
  • 1
  • 21
  • 39

2 Answers2

4

You can pass a data object to any route like that:

...
{
   path:'dashboard',
   component:DashboardComponent,
   canActivate:[
      AuthGuard
   ],
   data:{
      roles: ['ROLE_ADMIN', 'ROLE_EDITOR', 'OTHER_ROLE'],
      // any other relevant data to make your checks
   }
},
...

Then in your AuthGuard you can retrieve the data like:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    ...
    const roles = route.data[ 'roles' ] as Array<string>;

    // Do other checks here
    ...
}
Maxime Lafarie
  • 2,172
  • 1
  • 22
  • 41
1

You have two options.

First is to use params or queryParams.

canActivate(
  route: ActivatedRouteSnapshot, 
  state: RouterStateSnapshot): boolean {
  const userType = router.paramMap.get('userType');
}

Second is to use the dependency injection.

constructor(
  private router: Router,
  private AuthService: AuthServiceService,
  @Inject(CURRENT_USER) user: User,
) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  const userType = this.user.type;
}
Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79