Gáb*_*mre 6 angular2-routing angular2-modules angular
我有一个主模块和一些子模块.我想在它们之间指定一些不平凡的路由.
我更喜欢在子模块中定义子模块的路径.例如:
@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 {}
Run Code Online (Sandbox Code Playgroud)
我想用自己的内部路由导入这个模块,但我想让它的整个路由前缀.
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 {}
Run Code Online (Sandbox Code Playgroud)
此设置创建以下路由:/country,/country/list等,但我想让它们像这样前缀:
/settings/country/settings/country/list/settings/country/create我想通过另一个路由访问其他模块,例如CityModuleunder /otherstuff/city/create和/ othertuff/city/list`.
我的问题:
UPDATE
接受的答案是最好的方法:在模块中创建路径,在外部注册它们.因此,您可以修改路线,例如前缀(这是我想要的),您可以定义防护,覆盖或过滤它们等.
玩这个路由的东西,我刚刚找到一个干净的方式,我想分享,处理没有头痛的子模块的路线,更喜欢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;
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以将该Entrypoint导入到要放置路径的父模块中:
@NgModule({
imports: [
...
RouterModule.forRoot([
{ path: '', pathMatch: 'full', component: HomeComponent },
{ path: 'settings', loadChildren: CountryEntrypoint }
]),
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
你去吧!您现在可以使用settings/country/list和来访问子模块组件settings/country/list.
警告
小心不要导入CountryModule到父模块中@NgModule,因为它会覆盖路径外的settings路由.让路由器完成这项工作.
请享用!
在你的appRoutes中添加子路径
const appRoutes = [
{ path: '', component: HomeComponent },
{
path: 'settings',
component: CountryComponent,
canActivate: [AuthGuard],
children: COUNTRY_ROUTES
},
];
Run Code Online (Sandbox Code Playgroud)
创建单独的路由文件
export const COUNTRY_ROUTES:Routes = [
{ path: 'country', redirectTo: 'country/list' },
{ path: 'country/list', component: CountryListComponent },
{ path: 'country/create', component: CountryCreateComponent },
];
Run Code Online (Sandbox Code Playgroud)
在CountryComponent.html中
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4620 次 |
| 最近记录: |