Angular2第二级儿童路由第一个孩子的根源



我正在尝试创建一个多级路由层次结构。这样的东西:

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>

我期望获得url localhost的以下内容:4200/core/item/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匹配 - 没有组件可以渲染。它检查了孩子。第一个孩子具有路径item,并且与段item匹配,因此它应用了此分支。它永远不匹配{path:'',component: CoreComponent}叶子。路由器继续匹配,直到消耗整个URL为止。

您将拥有以下配置的期望:

const routes = {
  path: 'core',
  children: [
    {
      path: '',
      component: CoreComponent,
      children: [
        {
          path: 'item',
          children: [
            {
              path: '',
              component: ItemComponent
            }
          ]
        }
      ]
    }
  ]
};

最新更新