【问题标题】:How to reference a provider in static class methods?如何在静态类方法中引用提供者?
【发布时间】:2016-02-17 08:52:20
【问题描述】:

有没有办法在静态类方法中引用在引导时提供的服务?

目前没有任何代码,但我一直在尝试使用 Injector like here 的标准/样板语法。当我resolveAndCreate() 一个服务(也尝试过其他 Injector 方法...)时,会创建新实例并覆盖引导实例。

预期用例是 @CanActivate() 装饰器。我一直在做糟糕的解决方法(-:在服务准备好时设置 window["__ready__"] 并在装饰器中使用它......

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    一种解决方案是将在引导时创建的注入器的引用存储在专用单例中。

    bootstrap(App, [Auth, ROUTER_PROVIDERS])
    .then((appRef: ComponentRef) => {
      // store a reference to the injector
      appInjector(appRef.injector);
    });
    

    单例如下:

    let appInjectorRef: Injector;
    export const appInjector = (injector?: Injector):Injector => {
        if (injector) {
          appInjectorRef = injector;
        }
    
        return appInjectorRef;
    };
    

    然后你就可以像这样访问服务了:

    let injector: Injector = appInjector(); // get the stored reference to the injector
    let auth: Auth = injector.get(Auth); //get the service from the injector
    

    这是一个 Plunker,您可以在其中看到这一点。 (我不是 plunker 的作者,但这对我真的很有帮助):http://plnkr.co/edit/SF8gsYN1SvmUbkosHjqQ?p=preview

    【讨论】:

    • 很好,谢谢!我稍后会尝试实现它,但看起来很有希望 (;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多