简体   繁体   English

如何在Angular5中延迟加载不同的路由

[英]How to lazy load different routes in Angular5 correctly

I am trying to lazy load a module that has children routes. 我正在尝试延迟加载具有子路由的模块。 But so far only the main component keep loading. 但是到目前为止,只有主要组件在继续加载。 Here is my lazy loading routes module. 这是我的延迟加载路线模块。

export const routes: Routes = [
   { 
    path: '', 
    component: Notfound404Component, pathMatch: 'prefix',
    children: [
      { path: '', pathMatch: 'full', redirectTo: '404' },
      { path: '404', component: Notfound404Component },
      { path: '403', component: Notfound403Component }
    ] 
   }

And in my app.routes module I did this : 在我的app.routes模块中,我做到了:

 { path: 'error/403', loadChildren: './errors/errors.module#ErrorsModule'},
  { path: 'error', loadChildren: './errors/errors.module#ErrorsModule'}

Expected behavior is that localhost:4200/error loads the Notfound404Component component and localhost:4200/error/403 loads the Notfound403Component 预期的行为localhost:4200/error加载Notfound404Component组件,而localhost:4200/error/403加载Notfound403Component

Unfortunately it only loads the Notfound404Component on both routes. 不幸的是,它仅在两条路由上都加载Notfound404Component

How can I achieve this? 我该如何实现?

you must put this line to parent route 您必须将此行放到父路线

{ path: '', pathMatch: 'full', redirectTo: '/' },

and in child route replace 并在子路线中替换

{ path: '', pathMatch: 'full', redirectTo: '404' },

with this 有了这个

{ path: '', component: Notfound404Component },

your routing should be like 你的路线应该像

Solution 1: 解决方案1:

export const routes: Routes = [
   { 
    path: '', 
    component: Notfound404Component,
    children: [
      { path: '', pathMatch: 'full', redirectTo: '404' },
      { path: '404', component: Notfound404Component },
      { path: '403', component: Notfound403Component }
    ] 
   }

Solution 2: 解决方案2:

export const routes: Routes = [
   { 
    path: '', 
    component: Notfound404Component,
    children: [
      { path: '', component: Notfound404Component},
      { path: '404', component: Notfound404Component },
      { path: '403', component: Notfound403Component }
    ] 
   }

NOTE: Make sure you create parent component for child route 注意:确保为子路由创建父组件

For eg: <router-outlet></router-outlet> 例如: <router-outlet></router-outlet>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM