首页 文章

Angular 2在child中添加了指向根路由器的routerLink

提问于
浏览
5

目前我正在使用Angular 2 Beta 8开发一个Web应用程序 . 现在,当使用routerLink指令时,我遇到了嵌套路由的问题 .

路由器层次结构是:

AppCmp
|-> NewItemFormCmp
|-> UserDashboardCmp
    |-> MyItemsCmp

涉及的组件是:

@Component({
    ...
})
@RouteConfig([
    {component: NewItemFormCmp, name: 'NewItemForm', path: '/item/new'},
    {component: UserDashboardCmp, name: 'UserDashboardCmp', path: '/me/...', useAsDefault: true}
])
export class AppCmp {

}


@Component({
    ...
})
@RouteConfig([
    {component: MyItemsCmp, name: 'MyItemsCmp', path: '/items', useAsDefault: true}
])
export class UserDashboardCmp {

}


@Component({
    template: `
        ...
           a([routerLink]='["NewItemForm"]'
        ...
    `
})
export class MyItemsCmp {

}

嵌套到MyItemsCmp的路由工作完全正常 . 现在我想在MyItemsCmp中实现一个按钮,使用如组件模板中所示的routerLink指令导航到NewItemFormCmp .

加载Component'MyItemsCmp'时,模板的所有元素都在浏览器中呈现 . 但是NewItemFormCmp的链接不起作用,并且控制台中存在异常 .

Uncaught EXCEPTION: Component "MyItemsCmp" has no route config. in [["NewItemForm"] in MyItemsCmp@x:xxx]

在构造函数中注入路由器时,我可以导航到RootUser并使用“导航”导航到给定路由 .

如何使用RouterLink指令从二级子组件导航到一级子组件?

谢谢,菲利普

3 回答

  • 1

    如果你想改变它应该是根路由

    <a[routerLink]='["/NewItemForm"]'
    
  • 10

    组件实例化期间的RouterOutlet指令创建ChildRouter并将其作为“路由器”注入其中 . 因此,动态插入到RouterOutlet的组件有自己的嵌套路由器(它们上没有RouteConfig) . 这些路由器就像树叶 .

    这就是为什么它抱怨这个路由器主机组件没有配置路由 .

    你所要做的就是像这样写:

    <a [routerLink]="['../NewItemForm']">

    在路由器树中退一步

    (在Angular 2.0.0-beta.9中为我工作)

  • 0
    import {Router} from 'angular2/router';
    
    <button (click)="goToParent()">Goto Parent</button>\
    
    export class MyItemsCmp {
    
      constructor(router:Router){
          this.router=router;
      }
    
      goToParent()
      {
        this.router.parent.navigate(['/item/new']);
      }
    
    }
    

    Check this example with my routing, it does what you need

相关问题