【问题标题】:Get instance of component on active route in Angular2's router?在 Angular2 的路由器中获取活动路由上的组件实例?
【发布时间】:2018-01-07 22:59:46
【问题描述】:

如果我调用 Router.routerState.snapshot,我知道 Angular2 中的 ActivatedRouteSnapshot.component 包含对激活路由的引用/类,但是如何为组件类获取当前(或最小:创建的)实例?

Injector.get(..) 不返回组件实例,创建组件的新实例也无济于事(我)。

【问题讨论】:

  • 你能详细说明你在做什么吗?你想从哪里获得对组件类的引用?什么组件?
  • 组件(取决于环境)有时将属性 (showFooter) 设置为 true,有时设置为 false - 这取决于它从 REST 端点接收的数据。如果为 false,则包含 <router-outlet ...><app-footer ...> 的 App 组件应隐藏或显示页脚。

标签: angular components angular2-routing


【解决方案1】:

你可以使用

<router-outlet
  (activate)='onActivate($event)'
  (deactivate)='onDeactivate($event)'></router-outlet>

其中$event 是组件实例,例如将其分配给服务以使其全局可用。

另见https://angular.io/api/router/RouterOutlet

您还可以创建一个自动执行此操作的自定义 &lt;router-outlet&gt; 组件。

【讨论】:

  • 很高兴听到:)
【解决方案2】:

您应该能够通过 ActivateRoute 获得它。

例如,如果您有 Injector 服务:

const activatedRoute: ActivateRoute = this.injector.get(ActivatedRoute);

然后

component reference: this.injector.get(activatedRoute.component);

但是,这仅在您使用的注入器实例引用该组件本身时才有效。

在我的示例中,这可用于从该视图的子视图中查找 ViewComponent。

|- ViewComponent
  |- ChildComponent
    |- ChildComponent
      ... injector here -> using the code above, gets the ViewComponent' instance 
  |- ChildComponent

这可能不适用于您的实例,但是,希望这可能对某人有所帮助。

【讨论】:

    猜你喜欢
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多