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

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

问题描述

是否有一种干净的方法来获取对当前路由组件的引用?

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

这似乎有效,但看起来很笨拙:

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天全站免登陆