在Angular 2的路由器中获取当前路由组件的引用?

wan*_*ist 6 angular2-routing angular

是否有一种干净的方式来获取当前路线的组件?

这似乎有效,但似乎非常hacky:

 this.router.currentInstruction.
  component.componentType.prototype.somePropertyOrFunction();
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 6

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

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

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

@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);
    }
 }
Run Code Online (Sandbox Code Playgroud)

然后,您将能够以这种方式访问​​组件实例:

var component = this.service.getCurrentRouteComponent();
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,为什么在activateRoute中没有对组件实例的引用,有时将它放在那里非常方便 (3认同)