【问题标题】:Use RouterLink from a nested component使用嵌套组件中的 RouterLink
【发布时间】:2016-03-25 14:36:45
【问题描述】:

使用 Angular 2 beta.0

我有一个这样的组件结构

App (Has RouteConfig)
 -> List 
 | -> ListItem (Want to use RouterLink from here)

这会导致错误:Component "List" has no route config.

所以我像这样在List 组件上放置了一个RouteConfig...

@RouteConfig([
  {path: '/:id', name: 'Details', component: Detail}
])

但我得到一个像Error: Child routes are not allowed for "/list". Use "..." on the parent's route path.这样的角度错误

我尝试在该路由配置中的 /list 路径之前和之后添加这 3 个点...但没有成功。

路由器上的文档非常简单,虽然我知道这应该基于 ui-router,但我没有看到添加嵌套路由的并行

【问题讨论】:

  • 这取决于您如何使用您的 routerLink。例如,假设您想从ListItem 转到App(仅有的两个带有RouteConfig),所以您指定routerLink="['/SomeRouteInApp']"(注意/,这使它成为绝对,您正在上升!)。如果您想保持它相对于您所在的组件,您可以使用./ 指定 routerLink 或根本不使用斜杠。如果您发布您的 routerLink,它会更容易看到,并且复制会更好(对不起,长评论)。

标签: angular angular2-routing


【解决方案1】:

你可以像这样在父组件中使用它:

@RouteConfig([
  {path: '/', component: HomeComponent, as: 'Home'},
  {path: '/list/...', component: ListComponent, as: 'List'}
])

然后在您的ListComponent 中定义您的子路由:

@RouteConfig([
  { path: '/:id', component: ListItem, as: 'ListItem' }
])

确保ListComponent 也有<router-outlet></router-outlet>..

【讨论】:

    【解决方案2】:

    如果您要做的是使用一个子组件中的 routerLink 来实际转到您父级配置的路由之一,那么您不需要放置任何 RouterConfig 在子节点上,您只需要确保在父节点中正确配置了路由,然后在子节点装饰器内的子指令属性中添加 ROUTER_DIRECTIVES 常量。

    会是这样的:

    家长:

    import { ROUTER_PROVIDERS, RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router';
            :
        (some more imports)
            :
    @Component({
            :
        directives: [ROUTER_DIRECTIVES],
        providers: [ROUTER_PROVIDERS],
            :
    })
    
    @RouteConfig([
      {path: '/:id', name: 'Details', component: Detail}
    ])
    

    孩子:

    import { ROUTER_DIRECTIVES } from 'angular2/router';
        :
        :
    @Component({
        :
        directives: [ROUTER_DIRECTIVES],
        :
    })
    

    另外,不要忘记正确配置您的 routerLink,方法是提供您希望将用户发送到的路由作为数组的第一个参数,然后将您要发送的参数添加到使用您在 RouteConfig 中指定的相同名称来定位路由,如下所示:

    <a [routerLink]="['Details', { id: product.productId }]"> Details link </a>
    

    【讨论】:

      猜你喜欢
      • 2019-04-08
      • 2020-11-14
      • 2017-12-31
      • 1970-01-01
      • 2020-08-06
      • 2016-09-18
      • 2015-09-25
      • 2017-02-14
      • 2021-12-16
      相关资源
      最近更新 更多