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

喜夏-厌秋 提交于 2019-12-18 13:26:46

问题


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



来源:https://stackoverflow.com/questions/40799478/how-to-lazy-load-a-route-as-a-child-route-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!