【问题标题】:Angular 2 using the top level router outlet for all descendantsAngular 2 为所有后代使用顶级路由器插座
【发布时间】:2017-09-08 00:38:52
【问题描述】:

我有一个顶级组件,其中包含用户可以访问的所有功能,例如帐户或个人资料页面,还包含具有自己的子页面的功能。我以这种方式得到了一个深度嵌套的路由树,但是我目前不希望在视图上表示相同的结构。每个组件的内容都应该显示在 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。

我尝试了所有我能找到的不同配置,创建了命名的 outlets 然后调用它们,但通常我得到一个错误,即没有找到主要的 outlets,或者它与提供的 URL 不匹配。

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

【问题讨论】:

  • 转发到同一个路由器出口是什么意思?应该呈现相同的内容,还是应该进行重定向?
  • 我的意思是与 /user/profile 和 /user/shop/9/create 路由(例如)关联的内容应该加载到位于UserComponent 的 HTML。

标签: angular angular2-routing


【解决方案1】:

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

如果您需要在两种不同的用途中使用“UserComponent”(一种用于基于用户的详细信息,另一种用于商店信息的布局),那么您可以在“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”而不是其他任何东西。

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 2017-03-04
    • 2017-04-04
    • 1970-01-01
    • 2016-12-30
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    相关资源
    最近更新 更多