2017-05-30 84 views
1

我想创建一个多级路由层次结构。事情是这样的:Angular2二级子路由到第一个孩子的根insteead

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 /核心/ item

APP Works! 
core module 
item works 

但是,我越来越:

APP Works! 
item works 

因此,项目路由器可直接在应用模板,而不是核心模板渲染。

回答

1

如果合并的路线,您会收到以下路由树:

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

这似乎像以前一样被给予同样的结果。 –

+0

@SourabhDev,你是什么意思?我解释了为什么你没有你期望的结果 –

+0

这种方法确实能够达到预期的结果。看起来core.router和item.router在这里没用。我希望有一种更清晰的方式来按组件和子组件分隔路线。 –

相关问题