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

2020-02-26 11:49发布

问题:

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 /lazy should render the LazyModule into the <router-outlet> of my MainComponent.

Then it will switch between that DummyComponent and the lazy loaded Module.

Instead now that lazy loaded Module will be rendered into the AppComponent..

Any ideas?

回答1:

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