Ashutosh Jha
Ashutosh Jha

Reputation: 16337

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'

Upvotes: 8

Views: 9915

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

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

Upvotes: 16

Related Questions