获取对Angular 2路由器中当前路由的组​​件的引用? [英] Get a reference to a component of current route in Angular 2's router?

查看:137
本文介绍了获取对Angular 2路由器中当前路由的组​​件的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种干净的方法来引用当前路线的组成部分?

Is there a clean way to get a reference to the component of current route?

这似乎可行,但似乎很hacky:

This seems to work, but seems very hacky:

 this.router.currentInstruction.
  component.componentType.prototype.somePropertyOrFunction();

推荐答案

实际上,您无权使用表达式访问与当前路由关联的组件实例.您仅获得组件类型.这就是为什么您需要使用原型,但获得对函数的引用,而不对组件实例的方法的引用的原因.

In fact, you don't have access to the component instance associated to the current route with your expression. You only get the component type. That's why you need to use the prototype but you get a reference to function and don't reference to methods of the component instance.

主要后果是,未定义this关键字(如果在方法中使用).

The main consequence will be that the this keyword (if used within the methods) will be undefined.

要访问与当前路由关联的组件实例,可以利用OnActivate钩子接口在激活路由时将此实例设置为共享服务:

To access the component instance associated to the current route, you could leverage the OnActivate hook interface to set this instance into a shared service when the route is activated:

@Component({
  selector: 'some-cmp',
  template: `
    <div>routerOnActivate: {{log}}</div>
  `})
  export class SomeCmp implements OnActivate {
    constructor(private service:RouteStateService) {
    }

    routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction) {
      this.service.setCurrentRouteComponent(this);
    }
 }

然后,您将可以通过以下方式访问组件实例:

Then you would be able to access the component instance this way:

var component = this.service.getCurrentRouteComponent();

这篇关于获取对Angular 2路由器中当前路由的组​​件的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆