3

是否可以使用 配置“终端”路由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 }
  ]},
  //...
];

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

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

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

...有效,但感觉像是一种解决方法。

有没有更好的办法?

4

2 回答 2

3

An even simpler version of your 3rd attempt is to simply use an empty path with nothing else in it, not even a component:

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

Victor Savkin has written about componentless routes, although he doesn't go so far as to use a completely empty route like this (his examples contain either a redirect or a children property).

Depending on your setup, you can even take it a step further and remove the /a path. I have a routes declaration like this in a feature module, lazy-loaded under path: 'module-path':

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

So routing to /module-path loads AListComponent which contains an empty <router-outlet>, and routing to /module-path/5 populates the outlet with ADetailsComponent.

于 2016-08-26T04:25:01.000 回答
1

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

于 2016-08-01T08:43:16.387 回答