2017-05-30 5 views
1

マルチレベルルーティング階層を作成しようとしています。このような何か:Angular2の第2レベルの子が最初の子のルートインスタンスにルーティングする

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 /コア/品目

APP Works! 
core module 
item works 

しかし、私は取得しています:

APP Works! 
item works 

だから、アイテムルータが直接アプリテンプレートの代わりに、コアテンプレートでレンダリングされます。

答えて

1

あなたのルートをマージする場合は、次のルーティングツリーを取得する:あなたが/core/itemに移動すると

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

、ルータは、ルーティングパスで各セグメントを一致させようとします。したがって、最初に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はここでは役に立たないようです。私は、コンポーネントとサブコンポーネントによってルートを分離する、よりきれいな方法があることを望みます。 –

関連する問題