Ranoy
Ranoy

Reputation: 108

lazy load a feature module from a library

I have an angular 8 application, I want to lazy load a feature module from a library. It works in ng serve mode , but ng build --prod fails . Example code

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { AppGuardService } from './app-config/app-guard.service';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '',
    canActivate: [AuthGuardService],
    children: [
      {
        path: '',
        canActivate: [CustomerGuardService],
        component: AppComponent,
        children: [
          {
            path: '',
            pathMatch: 'full',
            redirectTo: 'home'
          },
          {
            path: 'home',
            component: HomeComponent
          },
          {
            path: 'featureModule',
            loadChildren: () => import('@custom/lib').then(m => m.AppModule)
          }
        ]
      }
    ]
  },
  {
    path: '**',
    redirectTo: '/'
  }
];

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

I could think of a wrapper module for each of my micro applications but it does not feel a clean solution

Upvotes: 1

Views: 1364

Answers (2)

BackToReal
BackToReal

Reputation: 141

Try to replace path='' after Children to a meaningful path, that way may cause confusion when redirecting.

Upvotes: 0

Wasim
Wasim

Reputation: 724

Just add data: { preload: true } after path and before loadChildren : () => in your feature module routing. Like this

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { AppGuardService } from './app-config/app-guard.service';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '',
    canActivate: [AuthGuardService],
    children: [
      {
        path: '',
        canActivate: [CustomerGuardService],
        component: AppComponent,
        children: [
          {
            path: '',
            pathMatch: 'full',
            redirectTo: 'home'
          },
          {
            path: 'home',
            component: HomeComponent
          },
          {
            path: 'featureModule',
            data: { preload: true }, //This will do lazy loading
            loadChildren: () => import('@custom/lib').then(m => m.AppModule)
          }
        ]
      }
    ]
  },
  {
    path: '**',
    redirectTo: '/'
  }
];

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

Upvotes: 1

Related Questions