How we can fetch route parameters in lazily loaded module in Angular

836 views Asked by At

I have route like below, where am passing id as parameters. So the same ID I have to use inside the module for loading isolated translation file on a basis of route parameters.

const routes: Routes = [
  {
    path: 'flight/:id', loadChildren: () => import('./layout/base/base.module').then(m => m.BaseModule)
  },
];

Now in BaseModule file I have to use :id data for loading some data. Is there any way so I can read or fetch route data in BaseModule file.

2

There are 2 answers

0
J. S. On

You can use this configuration to access parameters from the parent route:

  RouterModule.forRoot(appRoutes, {
      paramsInheritanceStrategy: 'always'
    })

Now you can access :id in base.module. But better name your params more specifically when using this approach.

Another way would be to climb the router state up:

export function extractRoute(route: ActivatedRoute, component: any): ActivatedRoute {
  if (route && route.component !== component) {
    return extractRoute(route.parent, component);
  }
  return route;
}

You could use this function with the component that holds the router-outlet corresponding to the router config. For Example

AppComponent->RouterOutlet->

    const routes: Routes = [
      {
        path: 'flight/:id', loadChildren: () => import('./layout/base/base.module').then(m => m.BaseModule)
      },
    ];

The you could acces the id property with:

constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {
 const id = extractRoute(activatedRoute, AppComponent).snapshot.params.id;
}
0
Eldar On

In your BaseModule you can subscribe to the router events and then check the ActivatedRoute snapshot to get your id like below :

export class BaseModule {
  constructor( active: ActivatedRoute, router: Router) {
    router.events
      .pipe(
        filter(e => e instanceof NavigationEnd),
        filter((ne: NavigationEnd) => ne.url.includes("flights/"))
      )
      .subscribe(e => {
        console.log(active.firstChild.snapshot.params.id);
      });
  }
}

StackBlitz