Angular2路由:使用路由导入子模块+使其成为前缀

时间:2016-12-07 14:52:11

标签: angular angular2-routing angular2-modules

我有一个主模块和一些子模块。我想在它们之间指定一些不平凡的路由。

我更喜欢在子模块中定义子模块的路径。例如:

@NgModule({
    imports: [
        /*...*/
        RouterModule.forChild([
            { path: 'country', redirectTo: 'country/list' },
            { path: 'country/list', component: CountryListComponent },
            { path: 'country/create', component: CountryCreateComponent },
            /*...*/
        ])
    ],
    declarations: [/*...*/],
    exports: [
        RouterModule,
    ],
})
export class CountryModule {}

我想用自己的内部路由导入此模块,但我希望以整个路由为前缀。

const appRoutes = [
    { path: '', component: HomeComponent },
    /*... (basic routes)*/
];

@NgModule({
    imports: [
        /*...*/
        RouterModule.forRoot(appRoutes),
        CountryModule, // <- how to make its routing prefixed??
    ],
    declarations: [
        /*...*/
        AppComponent,
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule {}

此设置会创建以下路线:/country/country/list等,但我想将它们作为前缀:

  • /settings/country
  • /settings/country/list
  • /settings/country/create

我想通过其他路由访问其他模块,例如在CityModule和/ otherstuff / city / list`下的/otherstuff/city/create

我的问题:

  1. 是否可以导入具有自己路由的模块并使其路由前缀?
  2. 此外:有没有办法在两个子模块之间建立最终(前缀)路线的链接?
  3. 更新

    接受的答案是最好的方法:在模块中创建路线,在外部注册。因此,您可以修改路线,例如前缀(这是我想要的),你可以定义警卫,覆盖或过滤它们等。

2 个答案:

答案 0 :(得分:9)

玩这个路由的东西我刚刚找到一个干净的方式,我想分享,处理没有头痛的子模块的路线,更喜欢Angular。以OP案例为例,我建议你研究下面的代码:

CountryModule子模块添加一个实用程序函数,从路由器动态加载它,避免编译器警告有关用导出函数的引用替换箭头函数:

@NgModule({
  imports: [
    ...
    RouterModule.forChild([
      { path: 'country', pathMatch: 'full', redirectTo: 'list' },
      { path: 'country/list', component: CountryListComponent },
      { path: 'country/create', component: CountryCreateComponent },
    ])
  ],
  declarations: [ ... ],
  exports: [
    RouterModule,
  ],
})
export class CountryModule {}

export function CountryEntrypoint() {
  return CountryModule;
}

现在,您可以将该Entrypoint导入到您要放置路径的父模块中:

@NgModule({
  imports: [
    ...
    RouterModule.forRoot([
      { path: '', pathMatch: 'full', component: HomeComponent },
      { path: 'settings', loadChildren: CountryEntrypoint }
    ]),
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

你去吧! 您现在可以使用settings/country/listsettings/country/list来访问子模块组件。

警告

小心不要将CountryModule导入父模块的@NgModule,因为它会覆盖settings路径之外的路由。让路由器完成这项工作。

享受!

答案 1 :(得分:5)

你的appRoutes中的

添加子路线,如

const appRoutes = [
    { path: '', component: HomeComponent },
    {
    path: 'settings',
    component: CountryComponent,
    canActivate: [AuthGuard],
    children: COUNTRY_ROUTES
  },
];

创建单独的路线文件

export const COUNTRY_ROUTES:Routes = [
  { path: 'country', redirectTo: 'country/list' },
  { path: 'country/list', component: CountryListComponent },
  { path: 'country/create', component: CountryCreateComponent },

];

在CountryComponent.html

<router-outlet></router-outlet>