【问题标题】:Angular2 route-link from child component has no effect来自子组件的 Angular2 路由链接无效
【发布时间】:2016-05-23 02:06:41
【问题描述】:

当我在试验 Angular2 的路由器(2.0 beta 6)时,我遇到了一个关于从子组件调用 routeLink(或 router.navigate)的问题。

我的主要组件如下所示:

@Component({
  selector: 'myapp',
  template:`
  <div>
    <alink></alink>
    <router-outlet></router-outlet>
  </div>
  `,
  directives: [ROUTER_DIRECTIVES, ALinkComponent],
  providers: [ROUTER_PROVIDERS]
})
@RouteConfig([
    {
      path: '/first',
      name: 'First',
      component: FirstComponent,
      useAsDefault: true
    },
    {
      path: '/second',
      name: 'Second',
      component: SecondComponent
    }
])
export class MyApp {
}

&lt;alink&gt; 仅显示带有[routerLink]Second 的链接:

@Component({
  selector: 'alink',
  template: `<h3><a [routerLink]="['Second']">Should redirect to second</a></h3>`,
  directives: [ROUTER_DIRECTIVES],
  providers: [ROUTER_PROVIDERS]
})
export class ALinkComponent {
}

但是,当单击此链接时,什么也没有发生(控制台上甚至没有弹出消息)。 MyApp 模板中的链接可以完美找到。将(click)=... 处理程序与router.navigate(...) 一起使用也不起作用。

为了使routerLink 在任何嵌套组件中工作,我需要进行哪些更改?

一个完整的例子是可用的on Plunker

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    我让您的示例工作 here,但我必须添加大量代码。问题是ALinkComponent没有自己的RouteConfig,所以需要访问MyApp的路由器,调用它的navigate方法。

    【讨论】:

    • 非常感谢您的工作!您注入父级并使用其路由器的想法实际上使我走上了正确的道路。我刚刚找到了另一种对我来说似乎更容易但在某些情况下可能有缺点的方法:stackoverflow.com/a/35369679/2597135
    【解决方案2】:

    基于@MattScarpino's answer 非常有用的答案和this blogpost 我能够找到一种更简单的方法来执行此操作,而无需直接注入MyApp

    @Component({
      selector: 'alink',
      template: `<h3><a (click)="viewSecond()">Should redirect to second but does not</a></h3>`,
      directives: [ROUTER_DIRECTIVES],
      providers: [ROUTER_PROVIDERS]
    })
    export class ALinkComponent {
      constructor(injector: Injector) {
        this.router = injector.parent.get(Router);
      }
    
      viewSecond() {
        this.router.navigate(["Second"])
      }
    }
    

    这种解决方案的缺点可能是我们可能需要根据情况使用parentparent.parent。但是,我们避免显式引用顶级组件。

    【讨论】:

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