Search code examples
angularangular-routing

Angular 4 Lazy Loading with parameters


Hello I am attempting to lazy load a "detail module" while also sending parameters via the URL.

Here is my lazy loaded route:

{
    path: 'venue/:name/:id',
    loadChildren: () => System.import('../containers/activity-detail/activity-detail.module').then((file: any) => {
        return file.default;
    })
},

I would like to route to this 'activity-detail.module' and then load details using the ":name", and "id:" parameters.

The module which loads has its own routes file.

export const VenueDetailRoutes: Route[] = [
    {
        path: '',
        redirectTo: 'venue/:name/:id',  
        pathMatch: 'full'
    },
    {
        path: 'venue/:name/:id', 
        component: VenueDetailComponent,
        data: {
            shouldDetach: true, // Route will be resused. See CustomResuseStrategy.
            title: null
        }
    },
    {
        path: '**',
        redirectTo: '/'
    }

];

It seems without the first default object nothing works. I get the error:

{
    path: '',
    redirectTo: 'venue/:name/:id', 
    pathMatch: 'full'
},

TypeError: Cannot read property 'path' of null

With the default object in place I get the error:

Error: Cannot redirect to 'venue/:name/:id'. Cannot find ':name'.

Any help would be greatly appreciated.


Solution

  • I don't think that this works:

    {
        path: '',
        redirectTo: 'venue/:name/:id',  
        pathMatch: 'full'
    },
    

    It can't match an "empty" path to a path with parameters.

    The syntax for your lazy loaded route is quite a bit more complex than mine. Mine looks like this:

    {
        path: 'movies',
        loadChildren: './movies/movie.module#MovieModule'
    },
    

    Notice that "parent" route ('movies' in this example) is defined here on the lazy loaded route, and NOT repeated in the loaded modules routes.

    For example:

    RouterModule.forChild([
      { path: '', component: MovieListComponent },
      { path: 'search', component: MovieSearchComponent },
      { path: ':id', component: MovieDetailComponent }
    ])
    

    I would think in your case that the loaded module's routes should look something like this:

    export const VenueDetailRoutes: Route[] = [
        {  
           path: ':name/:id', 
           component: VenueDetailComponent,
            data: {
                shouldDetach: true, // Route will be resused. See CustomResuseStrategy.
                title: null
            }
        }    
    ];
    

    (Though you may want to consider leaving off the custom reuse strategy until you have the basic routes working.)