Search code examples
angularlazy-loadingangular-routing

Angular router lazy loading: two different modules which start with the same path


I have two modules each have two child routes.
First module uses routes like:
items/:id
items/:id/print

The second one:
items/:id/edit
items/:id/marketing

So I guess how to make a config for such a case:

export const appRoutes: Routes = [
    {
        loadChildren: './features/item-details/item-details.module#ItemDetailsModule',
        path: 'items/:id'
    },
    {
        loadChildren: './features/item-management/item-management.module#ItemManagementModule',
        path: 'items/:id'
    }
];

I don't want to unite this two modules since it's almost nothing in common.
And also I am not happy with an idea to separate it to 4 different modules.


Solution

  • Actually there is a way to do so with UrlMatcher. You can check a target url to load or not a module. https://angular.io/api/router/UrlMatcher

    const managmentMatcher = (segments: UrlSegment[]) => {
    
        return /^\/*items\/\d+\/(edit|marketings)\/*.test(segments.join('/')) ?
           { consumed: segments.slice(0, 2), posParams: { id: segments[1] } } : null;
    
    }
    
    export const appRoutes: Routes = [
        // special routes
        {
            loadChildren: './features/item-management/item-management.module#ItemManagementModule',
            matcher: managmentMatcher
        },
        // default routing for items/:id
        {
            loadChildren: './features/item-details/item-details.module#ItemDetailsModule',
            path: 'items/:id'
        }
    ];