首页 文章

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

提问于
浏览
2

我有一个顶级组件,其中包含用户可以访问的所有功能,如帐户或配置文件页面,但也包含具有自己的子页面的功能 . 我通过这种方式获得了一个深度嵌套的路由树,但是我目前不应该在UserComponent 's HTML. In short a user' s配置文件信息(/ user / profile)中包含的顶级路由器插座中显示内容,并为用户的第9个商店创建产品(/用户/商店/ 9 /创建)应转发到完全相同的路由器插座 .

这就是我的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
      },
    ]
  }
]

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

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

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

1 回答

  • 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”而不是其他内容 .

相关问题