延迟加载库中的功能模块

时间:2020-05-29 15:32:19

标签: lazy-loading angular8 angular-library

我有一个angular 8应用程序,我想从库中延迟加载功能模块。它可以在ng服务模式下工作,但是ng build --prod失败。 示例代码

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 {}

我可以为我的每个微型应用程序考虑一个包装器模块,但感觉不是一个干净的解决方案

2 个答案:

答案 0 :(得分:0)

只需在功能模块路由中的data: { preload: true }之后和path之前添加loadChildren : () =>。像这样

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 {}

答案 1 :(得分:0)

尝试在Children后面替换路径=''到有意义的路径,那样重定向时可能会造成混乱。