Route params not available in guards
Asked Answered
S

1

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.

Synchronism answered 25/8, 2017 at 15:1 Comment(1)
Please look at angular.io/api/router/CanActivate, canActivate is passed the route data.Noami
F
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); 
}
Fingernail answered 25/8, 2017 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.