2016-11-08 141 views
0

在我Angular2應用程序,我有一個路由模塊如下所示:奇怪的路由器行爲

RouterModule.forChild([{ 
      path: '', 
      component: HomeComponent, 
      children: [ 
       { path: '', redirectTo: 'explorer/0' }, 
       { path: 'explorer', redirectTo: 'explorer/0' }, 
       { 
        path: 'explorer/:id', 
        component: EntitiesExplorerComponent, 
        children: [ 
         { path: 'details', component: EntityDetailsComponent } 
        ] 
       }, 
      ] 
     }, 

正如你可以看到explorer路徑有一個孩子。

奇怪的是,如果我導航到/explorer/1我得到一個錯誤。 但是,如果我導航到/explorer/1/details一切正常。

我想介紹一個探險家,當我去/explorer/ID和實體的細節,當我去/explorer/ID/details

這是錯誤:(好像它不承認/explorer/ID

error_handler.js:47 EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'routes' of undefined 
TypeError: Cannot read property 'routes' of undefined 
    at getChildConfig (http://localhost:4200/main.bundle.js:61682:35) 
    at Recognizer.processSegmentAgainstRoute (http://localhost:4200/main.bundle.js:61648:27) 

回答

2

你的路由器的配置應該看起來更像是這樣的:

RouterModule.forChild([{ 
    path: '', 
    component: HomeComponent, 
    children: [ 
     { path: '', redirectTo: 'explorer' },    
     { 
      path: 'explorer',     
      component: AnotherComponentWithARouterOutlet, 
      children: [ 
       { 
        path: '', 
        redirectTo: '0', 
       }, 
       { 
        path: ':id', 
        component: EntitiesExplorerComponent, 
        children: [ 
         { path: '', redirectTo: 'details' }, 
         { path: 'details', component: EntityDetailsComponent } 
        ], 
       }, 
      ]     
     }, 
    ] 
}, 

如果您現在瀏覽的網址/explorer路由器應自動重定向到路由/explorer/0

您必須爲explorer -route創建另一個組件。該組件應在其模板中包含<router-outlet></router-outlet>以加載子級。孩子們是ids。如果路由中沒有給出id,路由器將重定向到0

:id路線有EntitiesExplorerComponentrouter-outlet。路由器想知道他必須加載到這個插座。所以你需要爲:id的孩子定義一條空路線。在我上面的示例中,我只是重定向到了details。如果你不想要這個,你應該爲這個''-空路線創建另一個組件。這個組件可能有一個按鈕,如:Click here to go to the details或類似的東西。

+0

謝謝菲利普。 在我的用例EntityDetailsComponent應該在EntitiesExplorerComponent上方。所以我需要同時顯示它們。 這就是爲什麼EntityDetailsComponent是EntityDetailsComponent的孩子。* 我注意到如果我把一個FakeComponent作爲EntitiesExplorerComponent的子元件:{path:'',component:Fake}它可以工作..但是也許有一個更乾淨的解決方案 – user3471528