Zze
Zze

Reputation: 18805

Angular 2 - Why do ActivatedRoute.params returns empty Object

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?

Upvotes: 2

Views: 5500

Answers (1)

Zze
Zze

Reputation: 18805

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.

Upvotes: 2

Related Questions