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

时间:2017-11-18 06:30:10

标签: angular angular5

我正在尝试延迟加载具有子路由的模块。但到目前为止只有主要组件继续加载。这是我的延迟加载路线模块。

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

在我的app.routes模块中,我做到了这一点:

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

预期行为localhost:4200/error加载Notfound404Component组件,localhost:4200/error/403加载Notfound403Component

不幸的是,它只在两条路线上加载Notfound404Component

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

你必须把这一行放到父路线

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

并在子路线替换

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

用这个

{ path: '', component: Notfound404Component },

答案 1 :(得分:0)

您的路由应该像

解决方案1:

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

解决方案2:

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

注意:确保为子路径创建父组件

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