I have an AccessGuard class in my project which its work is to determine if user can access to the route or not. I used the router.url
to get the current route
You need to use the method parameters to see the target route:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log(state.url);//'candidates'
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot)
this could help you:
Import ActivatedRouteSnapshot and RouterStateSnapshot:
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
Signature in the canActivate:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable {}
Check the state:
console.log("route-access",state);
Your Guard file would look something like this:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import { Observable } from 'rxjs';
import { AutenticacionService } from 'app/services/index';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router, private auth:AutenticacionService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
// console.log("route-access",state);
let _url:string="";
state.url.split("/").forEach(element => {
if(_url==="")
if(element!=="")
_url=element;
});
// console.log(_url);
return this.auth.check(_url)
.map((result) => {
if (result) {
return true;
} else {
this._router.navigate(['/']);
return false;
}
});
}
}
Current URL can be returned from RouterStateSnapshot as shown below,
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
console.log(state.url);
...
}