有没有一种干净的方法来获取当前路由组件的引用?
这似乎有效,但看起来很老套:
this.router.currentInstruction.
component.componentType.prototype.somePropertyOrFunction();
事实上,您无权使用表达式访问与当前路由关联的组件实例。您只能获取组件类型。这就是为什么您需要使用原型,但您获得对函数的引用,而不是对组件实例的方法的引用。
主要后果将是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);
}
}
然后您就可以通过以下方式访问组件实例:
var component = this.service.getCurrentRouteComponent();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)