Angular2二级子路由到第一个孩子的root insteead

时间:2017-05-30 13:26:54

标签: angular angular-routing

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

app

 |---core

       |---items

我的app路由器和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

因此,项目路由器直接在应用程序模板中呈现而不是核心模板。

1 个答案:

答案 0 :(得分:2)

如果合并路线,则会得到以下路由树:

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
            }
          ]
        }
      ]
    }
  ]
};