Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, how to include multiple components in a lazy loaded module?

On my homepage I have 4 links to components that all belong to a feature module called 'CrudModule'.

I'm wondering how to lazy load this module, this doesn't seem to work :

my app-routing.module.ts:

const routes: Routes = [
   { path: 'add', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
  , { path: 'search', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
  , { path: 'importer', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
  , { path: 'publier', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
];

In the official Angular docs only one component per module is mentioned, see
this example from https://angular.io/guide/lazy-loading-ngmodules :

app-routing.module.ts:

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(mod => mod.CustomersModule)
  },

customers-routing.module.ts:

  import { CustomerListComponent } from './customer-list/customer-list.component';
  
  const routes: Routes = [
  {
    path: '',
    component: CustomerListComponent
  }
];

The above path is set to an empty string. This is because the path in AppRoutingModule is already set to 'customers'.

Question : given that the path of a lazy loaded module always needs to be empty, does this mean that I should put all my components in different modules in order to implement lazy loading? In other words can a lazy loaded module handle multiple routes ? If so, how should I go about it?

like image 495
Ole EH Dufour Avatar asked Aug 07 '19 11:08

Ole EH Dufour


1 Answers

Normally, you'd have your routes in your main router module look something like this:

const routes: Routes = [
  {
    path: 'crud',
    loadChildren: () => import('./crudFeatureModule/crud.module').then(mod => mod.CrudModule)
  }
];

and call RouterModule.forRoot(routes).

Then, in your CrudModule, you would have:

const routes: Routes = [
  { path: 'add', component: AddComponent },
  { path: 'search', component: SearchComponent },
  { path: 'importer', component: ImporterComponent },
  { path: 'publier', component: PublierComponent }
];

and call RouterModule.forChild(routes).

Your URLs would then be /crud/add, /crud/search etc.

When you use loadChildren, the module you lazily load needs to know how to load child routes, i.e. it needs to register its routes to the RouterModule. Get what I mean?

P.S. It's generally considered best practice to stick to one language when building routes. Je présume par le nom des routes que tu es francophone :-) généralement on évite de mélanger français et anglais si possible ^^

like image 183
Will Alexander Avatar answered Oct 02 '22 14:10

Will Alexander