user1059939
user1059939

Reputation: 1715

Preserve Route Params in child routes?

In my case, I have some routes which look like this.

const appRoutes: Routes = [
   { 
       path: 'thing/:id',
       component: GenericComponent 
   },
   { 
       path: 'thing/special', 
       loadChildren: 'app/modules/thing/special.module#SpecialModule'
   }
];

Ultimately, SpecialModule requires lazy loading and it has its own child routes. At the moment the child routes are so:

const specialRoutes: Routes = [
    {
        path: '',
        component: SpecialComponent
    }
];

Essentially, SpecialComponent might extend GenericComponent since all it does is add new components (heavy) to the existing generic pool.

So GenericComponent is going to go and request the :id and is great, but SpecialComponent has lost the :id from the params. The ID became a child route. So now id is null and I can't load /mock-server/thing/null.

How do I retain or access the missing :id in my child route params?

Upvotes: 1

Views: 1239

Answers (1)

Frank Anneveld
Frank Anneveld

Reputation: 79

You can use the parent on the ActiveRouteSnapshot :

route.parent.params['id']

My way to go is to use a resolver in your route to get data on child routes etc... in this example : IDResolver

import { IDResolver } from '../../app.resolver';

const routes: Routes = [
  {
    path: ':id',
    component: LayoutComponent,
    children: [
      {path: '', redirectTo: 'something', pathMatch: 'full'},
      {path: 'something', component: SomethingComponent, resolve: {IDResolver}}
    ]
  }
];

And in your app.resolver

import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Injectable()
export class IDResolver implements Resolve<any> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    return Observable.of(route.parent.params['id']);
  }
}

export const APP_RESOLVER_PROVIDERS = [
  IDResolver
];

Don't forget to import into your main module

 providers: [APP_RESOLVER_PROVIDERS]

Hope this works for you Good luck :-)

Oh yes and in your Component.ts you have your "id" with:

  constructor(private route: ActivatedRoute) {
    route.snapshot.data.IDResolver.subscribe((result: any) => console.log(result.id));
  }

The reason why i use route resolver is it allows you to get data before navigating to the new route.

Upvotes: 1

Related Questions