我正在尝试创建多级路由层次结构。像这样的事情:
app
|---core
|---items
我的应用程序路由器和html如下:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{path: 'core', loadChildren: 'app/core/core.module#CoreModule'}
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
],
providers: [
]
})
export class AppRoutingModule { }
HTML:
<h1>
{{title}}
</h1>
<router-outlet></router-outlet>
我的核心路线和html如下:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router';
import { CoreComponent } from './core.component';
const coreRoutes:Routes = [
{path: 'item', loadChildren: 'app/core/item/item.module#ItemModule'},
{path: '', component: CoreComponent}
];
@NgModule({
imports: [RouterModule.forChild(coreRoutes)],
exports: [RouterModule] }) export class CoreRoutingModule { }
HTML:
core module
<router-outlet></router-outlet>
最后项目路由和html如下:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ItemComponent } from './item.component';
const itemRoutes:Routes = [
{path: '', component: ItemComponent}
];
@NgModule({
imports: [RouterModule.forChild(itemRoutes)],
exports: [RouterModule]
})
export class ItemRoutingModule {
}
HTML:
<p>
item works!
</p>
我期望得到以下网址 localhost:4200/core/item:
APP Works!
core module
item works
但是,我得到:
APP Works!
item works
因此,项目路由器直接在应用模板而不是核心模板中渲染。
最佳答案
如果合并路由,您将得到以下路由树:
const routes = {
path: 'core',
children: [
{
path: 'item',
children: [
{
path: '',
component: ItemComponent
}
]
},
{
path: '',
component: CoreComponent
}
]
};
当您导航到 /core/item
时,路由器会尝试将每个段与路由路径进行匹配。所以它首先匹配 core
- 没有要渲染的组件。它检查它的 child 。第一个子级具有路径 item
,并且它与段 item
匹配,因此它应用此分支。它永远不会匹配 {path:'',component: CoreComponent}
叶子。路由器继续匹配,直到整个 URL 被消耗。
通过以下配置,您将获得您所期望的结果:
const routes = {
path: 'core',
children: [
{
path: '',
component: CoreComponent,
children: [
{
path: 'item',
children: [
{
path: '',
component: ItemComponent
}
]
}
]
}
]
};
关于Angular2 第二级子路由到根而不是第一个子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44263611/