问题描述
我有一个主模块和一些子模块.我想在它们之间指定一些重要的路由.
I have a main module and some submodules. And I want to specify some not trivial routing between them.
我更喜欢在子模块中定义子模块的路由.例如:
I'd prefer defining the routes of a submodule within the submodule. E.g.:
@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 {}
我想用它自己的内部路由导入这个模块,但我想让它的整个路由带有前缀.
I want to import this module with its own internal routing, but I want to make its whole routing prefixed.
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
等,但我想让它们像这样前缀:
This settings creates the following routes: /country
, /country/list
, etc., but I want to make them prefixed like this:
/settings/country
/settings/country/list
/settings/country/create
我想通过另一个路由访问其他模块,例如/otherstuff/city/create
和/otherstuff/city/list` 下的 CityModule
.
There are other modules that I want to access via another routing, e.g. a CityModule
under /otherstuff/city/create
and /otherstuff/city/list`.
我的问题:
- 是否可以导入具有自己路由的模块并为其路由添加前缀?
- 此外:有没有办法在 2 个子模块之间建立与其最终(带前缀)路由无关的链接?
更新
公认的答案是最好的方法:在模块中创建路由,在外部注册它们.因此,您可以修改路线,例如为它们添加前缀(这是我想要的),您可以定义保护、覆盖或过滤它们等.
The accepted answer is the best way to do it: create the routes in the module, register them externally. Thus you can modify the routes, e.g. prefix them (this is what I wanted), you can define guards, override or filter them, etc.
推荐答案
在你的 appRoutes 中添加子路由,如
in your appRoutes add child route like
const appRoutes = [
{ path: '', component: HomeComponent },
{
path: 'settings',
component: CountryComponent,
canActivate: [AuthGuard],
children: COUNTRY_ROUTES
},
];
创建一个单独的路由文件
Create a separate routes file
export const COUNTRY_ROUTES:Routes = [
{ path: 'country', redirectTo: 'country/list' },
{ path: 'country/list', component: CountryListComponent },
{ path: 'country/create', component: CountryCreateComponent },
];
在 CountryComponent.html 中
In CountryComponent.html
<router-outlet></router-outlet>
这篇关于Angular2 路由:使用路由导入子模块 + 使其前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!