5

Why isn't id available in the below guard?

@Injectable()
export class ProjectDetailsGuard implements CanActivate {

    constructor(private activatedRoute: ActivatedRoute) { }

    canActivate() {
        const id = this.activatedRoute.snapshot.params['id'];

        console.log(id); // <-- undefined
    }

}

The same code works perfectly when implemented inside components.

Alex Lomia
  • 6,705
  • 12
  • 53
  • 87
  • 1
    Please look at https://angular.io/api/router/CanActivate, canActivate is passed the route data. – jlareau Aug 25 '17 at 15:06

1 Answers1

12

The ActivatedRoute can provide params only after the route is activated. If need to get params before it is activated i.e in canActivate method, try with ActivatedRouteSnapshot

canActivate(activatedRoute: ActivatedRouteSnapshot) {
    const id = activatedRoute.params['id'];

    console.log(id); 
}
Rajez
  • 3,717
  • 1
  • 14
  • 21