在 Angular2 的路由器中获取活动路由上的组件实例? [英] Get instance of component on active route in Angular2's router?
问题描述
我知道如果我调用 Router.routerState.snapshot
,Angular2 中的 ActivatedRouteSnapshot.component
包含对激活路由的引用/类,但是如何获取组件类它的当前(或最小:创建的)实例?
I know that ActivatedRouteSnapshot.component
in Angular2 contains the reference/class to the activated route if I call Router.routerState.snapshot
but how to get for the component class the current (or minimal: one created) instance for it?
Injector.get(..)
不返回组件的实例,创建组件的新实例也无济于事(我).
Injector.get(..)
does not return instances of components and creating a new instance of a component does also not help (me).
推荐答案
可以使用
<router-outlet
(activate)='onActivate($event)'
(deactivate)='onDeactivate($event)'></router-outlet>
其中 $event
是组件实例,例如将其分配给服务以使其在全球范围内可用.
where $event
is the component instance and for example assign it to a service to make it available globally.
另见https://angular.io/api/router/RouterOutlet
您还可以创建一个自定义的
组件来自动执行此操作.
You can also create a custom <router-outlet>
component that does that automatically.
这篇关于在 Angular2 的路由器中获取活动路由上的组件实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!