2017-05-30 85 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在這裏沒用。我希望有一種更清晰的方式來按組件和子組件分隔路線。 –

相關問題