Search code examples
angularlazy-loadingangular-routingangular-router

How to combine the use of Lazy Loding and parameterized routes in Angular


I currently have a working Angular 4 application with parameterized route with variables placeholders i.e. :zoneId :schemaId :id . I do not want to get rid of these but now that we are converting our app to use lazy loading, I cannot figure out where these parameterized routes go.

Currently app-routing.module.ts(which is imported into app-module.ts) has

const ROUTES: Routes = [
 {
        path: 'zones/:zoneId/schemas/:schemaId/errands/:id',
        component: ErrandDetailComponent

but all the examples I'm following such as these

https://toddmotto.com/lazy-loading-angular-code-splitting-webpack https://medium.com/@kouipheng.lee/lazy-loading-with-angular-4-29c23792b7f4

seemed to make me wipe away this path and give a generic name and use the loadChildren router which requires the path of the module #SomeModuleName This would make my code look something like this:

    const ROUTES: Routes = [
     {
            path: 'errandDetailComponent',
            loadChildren: './items/errands/errand-routing.module#ErrandRoutingModule',
            component: ErrandDetailComponent

Here is my issue because I don't know where I can use my parameterized routes now.

Just for completeness, my child router looks like this:

const errandRoutes: Routes = [
    {
        path: '', // APPARENTLY THIS MUST BE EMPTY FOR LAZY LOADING TO WORK SO CAN'T PUT PARAMETERIZED PATH IN HERE EITHER
        component: ErrandDetailComponent,
        resolve: { errand: ErrandResolver },
    }
];

@NgModule({
    imports: [
        RouterModule.forChild(errandRoutes)
    ],
    declarations: [ErrandRoutingModule],
    exports: [
        RouterModule
    ],
})
export class ErrandRoutingModule { }

Solution

  • For this setup you can use child routes to add the parameters back in.

    app-routing.module.ts

    const ROUTES: Routes = [
     {
          path: 'zones',
          loadChildren: './items/errands/errand-routing.module#ErrandRoutingModule',
    

    errands-routing.module.ts

    const errandRoutes: Routes = [
        {
            path: '',
            component: ErrandsComponent,
            children: [{
                path: ':zoneId/schemas/:schemaId/errands/:id',
                component: ErrandDetailComponent,
                resolve: { errand: ErrandResolver },
            }]
        }
    ];
    

    And you will just need a very thin ErrandsComponent for displaying the detail component.

    errands.component.ts

    @Component({
      selector: 'app-errands',
      template: '<router-outlet></router-outlet>',
    })
    export class ErrandsComponent{}