Angular 2二级子路由到根而不是第一个子

Angular2 second level child routing to root insteead of first child

我正在尝试创建多级路由层次结构。像这样:

app

 |---core

       |---items

我的app router和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:

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 - 没有要渲染的组件。它检查它的 children。第一个 child 有路径 item,它匹配段 item,所以它应用这个分支。它从不匹配 {path:'',component: CoreComponent} 叶。路由器继续匹配,直到整个 URL 被消耗。

您将通过以下配置获得您期望的结果:

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