Angular 2使用顶级路由器插座为所有后代

时间:2017-04-21 15:22:56

标签: angular angular2-routing

我有一个顶级组件,其中包含用户可以访问的所有功能,例如帐户或个人资料页面,还有包含自己子页面的功能。我用这种方式得到了一个深度嵌套的路由树,但是我目前不想在视图上表示相同的结构。每个组件的内容都应该显示在UserComponent的HTML中包含的顶级路由器插座中。简而言之,用户的个人资料信息( / user / profile )和用户第9店的产品创建( / user / shop / 9 / create )应转发到完全相同的路由器插座。

这就是我的 app-routing.modules.ts 的相关部分现在的样子:

path: 'user',
component: UserComponent,
canActivate: [AuthenticationGuard],
canActivateChild: [AuthenticationGuard],
children: [
  {
    path: '',
    redirectTo: '/user/profile',
    pathMatch: 'full'
  },
  {
    path: '*',
    redirectTo: '/user/profile',
    pathMatch: 'full'
  },
  {
    path: 'account',
    component: AccountComponent
  },
  {
    path: 'profile',
    component: ProfileComponent
  },
  {
    path: 'shop',
    children: [
      {
        path: ':id',
        component: ShopComponent,
        children: [
          {
            path: 'stores',
            component: StoresComponent
          },
          {
            path: 'modify',
            component: ShopModifyComponent
          }
        ]
      },
      {
        path: 'create',
        component: ShopCreateComponent
      },
    ]
  }
]

有些路线甚至没有组件。例如, user / shop 现在具有意义,但是当提供ID user / shop / 123 时,我想显示该商店的数据。还有一些路线应该包含多个参数,例如 user / shop / 123 / product / 321

我尝试了所有可以找到的不同配置,创建了命名插座然后调用它们,但通常我得到的错误是没有找到主插座或者它与提供的URL不匹配。

是否有一种简单的方法可以告诉所有后代(无论它们有多深)使用顶级路由器插座?

1 个答案:

答案 0 :(得分:0)

为什么不将'UserComponent'分配给'shop'路线配置?

如果您需要在两个不同的目的中使用'UserComponent'(一个用于基于用户的详细信息,另一个用于商店信息的布局),那么您可以在'UserComponent'模板中有两个出口并将其他出口名称分配给'shop'路线配置。

例如,您可能会喜欢这个

UserComponent

<router-outlet></router-outlet>
<router-outlet name="shop"></router-outlet>

然后是您的路线配置

{
    path: 'shop',
    component: UserComponent,
    outlet: 'shop',
    children: [
      {
        path: ':id',
        component: ShopComponent,
        children: [
          {
            path: 'stores',
            component: StoresComponent
          },
          {
            path: 'modify',
            component: ShopModifyComponent
          }
        ]
      },
      {
        path: 'create',
        component: ShopCreateComponent
      },
    ]
  }

如果您在路由到ShopComponent时不想显示任何内容,那么您只能在其中添加标记“router-outlet”而不是其他内容。

相关问题