0
votes

I'm trying to set up Angular (8) with lazy loading, but I just can't figure out how to make it work.

I have 3 modules, each others having different sub-routes :

  • module1 (inside of my app)
    • /home
    • /home/path1
    • /home/path2
  • module2 (presentation of the app, public)
    • index
    • presentation
    • features...
  • module3 (everything related to access)
    • login
    • register

Anyone would have a working example on how to make this function properly ?

Thanks

EDIT = here's the routing code of my main module :

{ path: 'home', component: HomeComponent, canActivate: [AuthGuardService], children: [ { path: '', component: DashboardComponent, canActivate: [AuthGuardService] }, { path: 'upgrade', component: StripeFormComponent, canActivate: [AuthGuardService] } ] }, ];

I tried to add lazy loading in the app-routing.module.ts. I reloaded my app, and looked like there was a bit less code, and my module looked like it was loaded lazily however when I tried to access the page, I got a blank page with no explanation. So I'm lost.

2
What have you tried so far? Can you add your code?yurzui
I just added a little more detailsTibo

2 Answers

1
votes

One way is you can decide on some common path names for components within each module ( like how you have 'home' for module 1). Then

  `const routes: Routes = [
   { path: 'home', loadChildren: () => import('./core/core.module').then(m => m.CoreModule) }
   { path: 'module2', loadChildren: () => import('<path to module>').then(m => m.module2) }
   { path: 'module3', loadChildren: () => import('<path to module>').then(m => m.module3) }
 ];`

Then within each module, you can define paths for each component likewise

`const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'asset/:id', component: AssetComponent },
  { path: 'sub/:id', component: SubCategoryComponent },
];`

This way, only the module which contains the component which matches with the path will be loaded.

1
votes

To set route in lazy loading in Angular 8 you have to define a module for the component you want to go, in which you have to define a routing.module:

 @NgModule({
      declarations: [
        DetailComponent,
      ],
      imports: [
        DetailRoutingModule,
        ChartsModule,
        CommonModule
      ]
    })

export class DetailModule { }

While YorComponentDetailRoutingModule is

const routes: Routes = [{
  path: '',
  component: DetailComponent,

}];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})


export class DetailRoutingModule { }

In app.routing module you can write:

const routes: Routes = [{
  path: '',
  component: PagesComponent,
  children: [
    {
      path: 'home',
      component: HomeComponent
    },{
      path: 'home/detail',
      loadChildren: () => import('./detail/detail.module')
      .then(m => m.DetailModule),
    } ...