2016-07-31 64 views
2

是否可以使用children配置“终端”路线,或者换句话说,具有“可选”children的路线。使用可选子项创建路线

我想创建一个可路由的主/细节视图,其中的细节最初不显示,并且当详细视图打开时,列表不会被销毁。

例如,导航至/a,然后在不破坏a的情况下导航至/a/1

首次尝试

const routes: RouterConfig = [ 
    //... 
    { path: 'a', component: AListComponent, children: [ 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
    //... 
]; 

...这个配置,下面的错误被抛出:

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: 'a'

第二次尝试

const routes: RouterConfig = [ 
    //... 
    { path: 'a', component: AListComponent }, 
    { path: 'a', component: AListComponent, children: [ 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
    //... 
]; 

...列表组件被销毁并重新创建,即如果它具有用户输入,则值将消失。

第三次尝试 - 创建一个“Empty”组件并默认加载它。

const routes: RouterConfig = [ 
    //... 
    { path: 'a', component: AListComponent, children: [ 
    { path: '', component: EmptyComponent }, 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
    //... 
]; 

...作品,但感觉像一个解决方法。

有没有更好的方法?

+0

如何使用不显示任何“可选”路由的虚拟组件? AFAIK你正在寻找什么不被支持。 –

+1

@GünterZöchbauer,感谢您的评论。你的建议基本上是我的第三次尝试 - 它有效,但并不“感觉正确”。但是,如果您将您的评论作为答案,我很乐意接受它。这种方法如何看待你?英雄之旅(https://angular.io/docs/ts/latest/tutorial/toh-pt2.html)使用* ngIf来实现这一点,但使用路由器感觉好一点。如果空分量方法看起来不太可怕,那么至少在目前这可能是一种前进的方式。 –

+0

恕我直言,如果'ngIf'非常合适,主要取决于您是否想在URL中反映状态。如果这不是'ngIf'没有必要或有用的话,那应该没问题。 –

回答

1

在我看来,最好的方法是在第三次尝试时不显示任何内容的空虚拟组件。

+0

谢谢!我希望这在未来的版本中变得更简单。 –

3

你的第三个尝试的一个更简单的版本是简单地用一个空路径与任何东西的,甚至不是一个组件:

const routes: Routes = [ 
    { path: 'a', component: AListComponent, children: [ 
    { path: '' }, 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
]; 

维克多Savkin有written about componentless routes,虽然他并没有走得这么远至于使用这样的完全空路线(他的例子包含redirectchildren属性)。

根据您的设置,您甚至可以更进一步并删除/a路径。我有一个功能模块中的routes声明这样,延迟加载path: 'module-path'下:

const routes: Routes = [ 
    { path: '', component: AListComponent, children: [ 
    { path: '' }, 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
]; 

所以路由到/module-path负载AListComponent其中包含一个空<router-outlet>,和路由/module-path/5填充与ADetailsComponent出口。

+0

谢谢您的建议!这看起来像一个改进。 –