How to lazy load a route as a child route/component

后端 未结 1 1722
我在风中等你
我在风中等你 2020-12-30 14:40

Let\'s take a look at my plunker: https://plnkr.co/edit/22RIoGsvzfw2y2ZTnazg?p=preview

I want to lazy load a Module as a child-route.

So the route /laz

相关标签:
1条回答
  • 2020-12-30 15:37

    If you want to lazy load a module, do not import it as you've done here :

    src/app.ts :

    import { LazyModule } from './lazy/lazy.module';
    ...
    
    @NgModule({
      imports: [ BrowserModule, RouterModule.forRoot(routes), LazyModule ]
    

    If you load a module (using import) it will be bundled into the main module instead of having a separated chunk.

    Replace it by :

    @NgModule({
      imports: [ BrowserModule, RouterModule.forRoot(routes) ]
    

    Then your routes should be like that :

    const routes = [
      {
        path: '',
        component: MainComponent,
        children: [
          {
            path: '',
            component: DummyComponent
          },
          // should be rendered as a CHILD of my MainComponent .. !!
          {
            path: 'lazy',
            loadChildren: 'src/lazy/lazy.module#LazyModule'
          }
        ]
      }
    ];
    

    Notice that loadChildren path starts from src now.


    For src/lazy/lazy.module.ts : You should have your routes defined (as it's needed for children modules) BUT your routes should be empty because they'll be suffixed by their parent's routes. (here : '/lazy').

    So if you put :

    const routes = [
      {
        path: 'lazy',
        component: LazyComponent
      }
    ];
    

    You expect to match /lazy/lazy to use your lazy component, which is not what you want.

    Instead use :

    const routes = [
      {
        path: '',
        component: LazyComponent
      }
    ]
    

    Here's the working Plunkr : https://plnkr.co/edit/KdqKLokuAXcp5qecLslH?p=preview

    0 讨论(0)
提交回复
热议问题