【问题标题】:Angular routing structure with nested child components具有嵌套子组件的角路由结构
【发布时间】:2019-08-26 12:07:18
【问题描述】:

我的 Angular 网络面板有一个 路由分支,如下所示:

const routes: Routes = [
  {
    path: 'home', component: HomeComponent, data: { },
    children: [
      { path: '', redirectTo: 'user', pathMatch: 'full' },
      {
        path: 'user', component: UserComponent, data: { },
        children: [
          { path: '', redirectTo: 'products', pathMatch: 'full' },
          { path: 'products', component: ProductsComponent, data: { }, 
            children: [
              { 
                path: ':id', component: ProductDetail, data: { } 
              },
            ]
          }
        ]
      }
    ]
  }
];

HomeComponent e UserComponent 只是儿童路由器插座

ProductsComponent 有一个产品列表

ProductDetail组件不出现,因为他的父亲ProductsComponent 没有“路由器插座” 在他的 html 中添加标签。

路由结构应该是怎样的,才能拥有一个拥有产品列表的父亲和拥有产品详细信息的孩子?

ProductsComponentProductDetail 设置为 UserComponent 的子级可以解决问题,但会在我的面包屑(home > user > listhome > user > detail)

我的目标是制作具有良好组件结构的面包屑。 喜欢主页 > 用户 > 列表 > 详细信息。

【问题讨论】:

  • 你不需要多个路由器插座,除非你做的辅助路由看起来不像你。
  • 也许我以非全面的方式写下上面的代码,假设我有这个路由:路径:'home',组件:HomeComponent,孩子:[{路径:'产品',组件: ProductsComponent }, { path: 'products/:id', component: ProductDetail } ] List 和 Detail 是兄弟,最好将 Detail 设置为 List 的子项?

标签: angular angular-ui-router angular2-routing


【解决方案1】:

我正在使用我的手机,请原谅任何格式错误,我稍后会进行编辑。

如果我理解正确的话,你应该可以通过使用下面的路由配置来实现你想要的:

const routes: Routes = [
  {
    path: 'home', component: HomeComponent, data: { },
    children: [
      { path: '', redirectTo: 'user', pathMatch: 'full' },
      {
        path: 'user', component: UserComponent, data: { },
        children: [
          { path: '', redirectTo: 'products', pathMatch: 'full' },
          { path: 'products', component: ProductsComponent, data: { }}, 
{path: 'products/:id', component: ProductDetail, data: { }} 
            ]
          }
        ]
      }
    ]
  }
];

您不需要嵌套组件来获得“漂亮”的路由,您可以在path 属性中创建它。

此外,如果您的 HomeComponent 和 UserComponent 只是路由器插座,您可以将所有内容简化为

const routes: Routes = [
    { path: 'home/user/products', component: ProductsComponent, data: { }}, 
    {path: 'home/user/products/:id', component: ProductDetail, data: { }} 
];

然后添加正确的redirectTo 子句。

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2016-12-19
    • 2016-06-21
    • 2018-11-06
    • 2018-01-11
    相关资源
    最近更新 更多