1
votes

I need to implement a route guard for my angular2 app based on the URL parameter that passed in the routing, for example:

http://myapp.com/test1/sites -------> where my routes use the test1 as a parameter :sitename

so if the passed parameter == test1 then canActivate return true, otherwise return false.

so how to implement this ?

2

2 Answers

2
votes

Route declaration:

{
  path: ':sitename/sites',
  component: SomeComponent,
  canActivate: [CanActivateSite]
}

Then the guard implementation:

@Injectable()
class CanActivateSite implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot): boolean {
    return route.params.sitename == 'test1';
  }
}
0
votes

A route guard class can implement the CanActivate interface which forces you to define a canActivate function. This function takes in 2 parameters: ActivatedRouteSnapshot and RouterStateSnapshot. Take a look at ActivatedRouteSnapshot...it contains data about the route including an object of params.

https://angular.io/docs/ts/latest/api/router/index/ActivatedRouteSnapshot-interface.html