Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular nested routing with lazy loading issue

I have an app on which I need only the sign in functionality to be available at startup, and all remaining code should be lazy loaded after user authenticates.

I've created a core.module with a core-routing.module and a core.component to handle this, but the child components (for example DashboardComponent) are being rendered inside router-outlet element on app.component.html and not at core.component.html and so the header is not being displayed.

I've already searched and a lot, but couldn't find how to have this working.

app-routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: 'signin', pathMatch: 'full' },
  { path: 'signin', component: SigninComponent },
  { path: 'app', loadChildren: './core/core.module#CoreModule', canLoad: [AuthGuard] },
  { path: '**', redirectTo: 'signin' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

app.component.html

<router-outlet></router-outlet>

core-routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canLoad: [AuthGuard] },
  { path: '**', redirectTo: 'dashboard' }
];

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

core.component.html

<div id="header">
  <app-header></app-header>
</div>
<main id="content">
  <router-outlet></router-outlet>
</main>

dashboard-routing.module.ts

const dashboardRoutes: Routes = [
  { path: '',  component: DashboardComponent, pathMatch: 'full' }
];

@NgModule({
imports: [
  CommonModule,
  MaterialModule,
  SharedModule,
  RouterModule.forChild(dashboardRoutes)
],
like image 233
GCSDC Avatar asked Nov 22 '18 02:11

GCSDC


1 Answers

After trying it on many different ways, what worked for me was changing core-routing.module.ts to have a single route and including the lazy loaded modules as children inside it:

const routes: Routes = [
  {
    path: '',
    component: CoreComponent,
    children: [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      { path: 'dashboard', loadChildren: '../dashboard/dashboard.module#DashboardModule', canLoad: [AuthGuard] },
      { path: 'customers', loadChildren: '../customers/customers.module#CustomersModule', canLoad: [AuthGuard] },
      { path: 'history', loadChildren: '../history/history.module#HistoryModule', canLoad: [AuthGuard] },
      { path: 'processing', loadChildren: '../processing/processing.module#ProcessingModule', canLoad: [AuthGuard] },
      { path: '**', redirectTo: 'dashboard' }
    ]
  }
];

Hope this may help someone trying to implement the same functionality.

like image 131
GCSDC Avatar answered Nov 11 '22 06:11

GCSDC