【问题标题】:Inject an application level Service to @CanActivate将应用程序级服务注入@CanActivate
【发布时间】:2016-02-11 07:19:27
【问题描述】:

我想通过使用@CanActivate 路由生命周期事件来实现与Angular1.x 路由“resolve”类似的功能。

作为允许路由通过的触发器,我想使用在应用程序引导程序中定义的服务(这使其成为单个应用程序范围的实例)。

bootstrap(AppComponent, [ ROUTER_PROVIDERS, TestObjectModel ])

我看到我可以在该生命周期事件中使用依赖项的唯一方法是使用以下内容:

const injector = Injector.resolveAndCreate([TestObjectModel]); const testObjectModel = injector.get(TestObjectModel);

这确实为我提供了一个服务实例,但是一个新实例(不是应用程序范围内使用的实例)。

我也尝试了Injector.fromResolvedProviders,但没有更好的结果。

有什么方法可以让我接触到组件内的根 Injector?

【问题讨论】:

    标签: dependency-injection angular2-routing


    【解决方案1】:

    我在 http://embed.plnkr.co/SF8gsYN1SvmUbkosHjqQ/ 找到了这个解决方法。

    它可以工作,并允许我在生命周期挂钩中获取单个服务实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多