Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get requesting url in guard angular 2

How to get requesting url in guard service

HasPermissionService

@Injectable()
export class HasPermissionService implements CanActivate{
  private permissions = [];

  constructor(private _core:CoreService,private route1:Router, private _route:ActivatedRoute ,private route: ActivatedRouteSnapshot,private  state: RouterStateSnapshot) { 
    console.log('constructor calling ...');
    // console.log(this.route.url);
    this.permissions = this._core.getPermission();
    console.log('inside guard');
    console.log(this.permissions);
  }

  canActivate( ) {
    console.log(this.route);
    console.log(this._route);
    return true;
  }
}

but I am getting old url , from which I am coming from. How to get the current url?

routes

{path:'grade-listing',component:GradeListingComponent,canActivate:[HasPermissionService]}

I need to get 'grade-listing'

like image 618
Ashutosh Jha Avatar asked Jan 03 '17 09:01

Ashutosh Jha


1 Answers

Within the canActivate function the ActivatedRouteSnapshot and the RouterStateSnapshot is passed through as arguments:

@Injectable()
export class HasPermissionService implements CanActivate {

   private permissions = [];

   constructor(private _core: CoreService) { 
     this.permissions = this._core.getPermission();
   } 

   canActivate(
      route: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
    ): Observable<boolean>|Promise<boolean>|boolean {
       //check here
    }
}

You should start there to look at which route is being activated. The URL segments matched by this route are inside the route.url

CanActivate

like image 122
Poul Kruijt Avatar answered Oct 12 '22 07:10

Poul Kruijt