2016-11-08 140 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