2

I am trying to access the :id route parameter in a router guard, but for some reason, it always returns an empty Object{}.

Initially I didn't know how to do this, so I used this question to point me in the right direction, however it yields no result. The key difference between that and this is that my issue is in a guard.

This is my route declaration app-routing.module:

const dashboardRoutes: Routes = [
    {
        path: "dashboard/:id",
        component: dashboard.DashboardComponent,
        canActivate: [guard.LoggedInGuard],
        children: [
            {
                path: "",
                redirectTo: "home",
                pathMatch: "full"
            }, 
            ...

And this is my guard existsInDatabase.guard (I tried both params & queryParams):

constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute
) { }


canActivate() {
    console.log(this.activatedRoute.params);
    this.activatedRoute.params.subscribe(param=> {
        console.log(param); // logs empty Object{}
        console.log(param['id']); // logs undefined
    });
    this.activatedRoute.queryParams.subscribe(param=> {
        console.log(param); // logs empty Object{}
        console.log(param['id']); // logs undefined
    });
    return true;
}

The issue occurs when I try to navigate from

http://localhost:4200/dashboard/136364285

to:

http://localhost:4200/dashboard/136364285/dock/1654321

How do I get 136364285?

2
  • I don't have a real solution for this but while you don't have a real answer, maybe you can use "this.router.url.split('/')[4]" to get the id. Hope someone will save you :) Commented Apr 25, 2017 at 15:40
  • @Powkachu Thanks, I am thinking that maybe Günter was right (he deleted his answer) That for some reason the param has not yet been 'integrated' into the router... Commented Apr 25, 2017 at 23:04

1 Answer 1

2

I solved this issue by passing the following through to the canActivatefunction in my guard.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    console.log(route.params['id']); // logs 136364285
    return true;
}

Originally I was getting route: ActivatedRouteSnapshot in the constructor and even though I was using .snapshot, it was not yielding the intended result. No I recieve the route I am about to navigate to and can retrieve params from there.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.