嵌套路由和多个组件

时间:2017-10-12 09:06:12

标签: angular angular2-routing

我尝试在Angular 2中创建一个看起来像这样的视图:

releases-component
-----------------    -------------    --------------
| releases-list |    | rcs-list  |    | binaries-  |
| * release1    |    | * rc1     |    | list       |
|   release2    |    |   rc2     |    |            |
-----------------    -------------    --------------

其中三个部分中的每一部分都是一个组件,而releasesrcs包含一个列表,其中的链接应映射到以下路径:

  • releases - >列出releases组件
  • 中的所有版本
  • releases/:id/rcs - >列出rcs组件中包含id的版本的rcs
  • releases/:id/rcs/:no/binaries - >列出rc组件
  • 中选择的binaries的二进制文件

释放-component.html

<router-outlet></router-outlet>
<router-outlet name="rcs"></router-outlet>
<router-outlet name="binaries"></router-outlet>

路由

{
  path: 'releases',
  component: ReleasesComponent,
  children: [
    { path: '', component: ReleasesListComponent },
    {
      path: ':id/rcs',
      outlet: 'rcs',
      component: CandidateComponent,
      children: [
        { path: ':no/binaries', outlet: 'binaries', component: BinariesComponent }
      ]
    },
  ]
}

发布链接 - 显示rcs列表

{outlets: {rcs: release.id + '/rcs'}}

rcs链接 - 显示二进制文件列表

{outlets: {binaries: rc.id + '/binaries'}}

我尝试了所有不同类型的路线和链接定义,但我无法让它发挥作用。使用此当前解决方案,二进制文件根本无法显示,单击另一个rcs链接后,我收到以下错误:

TypeError: Cannot read property 'component' of null

1 个答案:

答案 0 :(得分:1)

This might sound ridiculously complex. But it's fairly simple. I suggest you have your routing like this:

{ path: 'releases', component: ReleaseListComponent, children: [
    { path: '', component: NotSelectedComponent },
    { path: ':id', component: ReleaseDetailsComponent, children: [
        { path: '', component: NotSelectedComponent },
        { path: 'rcs', component: RcsListComponent, children: [
            { path: '', component: NotSelectedComponent },
            { path: ':id', component: RcsDetailsComponent, children: [
                { path: '', component: NotSelectedComponent },
                { path: 'binaries', component: BinaryListComponent }
            ] }
        ] }
    ] }
] }

Now for each path that has a component with children on it, you'll have to place a <router-outlet></router-outlet>. And then it will figure out the rest on it's own.

So, by that I mean that following components will have a router-outlet inside their templates:

  • ReleaseListComponent
  • ReleaseDetailsComponent
  • RcsListComponent
  • RcsDetailsComponent

I wish I could style this to show you on the screen. But that's too much of effort and I would literally be spoon-feeding you in that case.

But here's how it will look on the UI:

enter image description here