【问题标题】:Storing injector instance for use in components存储注入器实例以在组件中使用
【发布时间】:2017-01-17 11:19:41
【问题描述】:

在 RC5 之前,我使用 appref 注入器作为服务定位器,如下所示:

启动.ts

bootstrap(...)
.then((appRef: any) => {
    ServiceLocator.injector = appRef.injector;
});

ServiceLocator.ts

export class ServiceLocator {
    static injector: Injector;
}

组件:

let myServiceInstance = <MyService>ServiceLocator.injector.get(MyService)

现在在 bootstrapModule().then() 中做同样的事情不起作用,因为组件似乎在承诺之前开始执行。

有没有办法在组件加载之前存储注入器实例?

我不想使用构造函数注入,因为我在由许多组件派生的基础组件中使用注入器,我宁愿不将注入器注入所有组件。

【问题讨论】:

    标签: angular


    【解决方案1】:

    基于类的解决方案。

    我经常需要从其他类使用的类中引用服务。 通过构造函数注入服务很麻烦,并且会导致调用类出现问题,这些类不需要给定的服务。

    在 Angular 8 中,我设置了一个库类:ServiceInjectorModule (也可以在子模块中使用)

    (来自stackoverflow上的类似答案)

    文件:service-injector.module.ts

    import { NgModule, Injector } from '@angular/core';
    
    export let ServiceInjector: Injector;
    
    @NgModule()
    export class ServiceInjectorModule {
      constructor(private injector: Injector) {
        ServiceInjector = this.injector;
      }
    }
    

    文件:my-lib.module.ts

    注意:您可以跳过此库模块,因为如果您有其他服务或模块要使用,它会更方便。如果你跳过它,直接将 ServiceInjectorModule 导入你的 AppModule。

    import { ServiceInjectorModule } from './service-injector.module';
    
    const impExpModules = [
      ...,
      ServiceInjectorModule,
      ...
    ];
    
    
    @NgModule({
      imports: [impExpModules],
      exports: [impExpModules]
      })
    export class MyLibModule {}
    

    将 MyLibModule 导入您的 AppModule 或最适合的位置。

    现在在您的组件或类中,简单地说:

    import { ServiceInjector } from '../modules/lib/service-injector.module';
    import { MyService } from '../services/my.service';
    
    
    export class MyCurrentClass {
    
      myService = ServiceInjector.get(MyService);
    
      ...
      
      myLocalFunction() {
          ...
          this.myService.myServiceFunction(...
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      对于今天的 TypeScript 和 Angular 5,在导入全局注入器时避免 WARNING in Circular dependency detected,首先声明一个帮助器,例如app-injector.ts:

      import {Injector} from '@angular/core';
      
      /**
       * Allows for retrieving singletons using `AppInjector.get(MyService)` (whereas
       * `ReflectiveInjector.resolveAndCreate(MyService)` would create a new instance
       * of the service).
       */
      export let AppInjector: Injector;
      
      /**
       * Helper to set the exported {@link AppInjector}, needed as ES6 modules export
       * immutable bindings (see http://2ality.com/2015/07/es6-module-exports.html) for 
       * which trying to make changes after using `import {AppInjector}` would throw:
       * "TS2539: Cannot assign to 'AppInjector' because it is not a variable".
       */
      export function setAppInjector(injector: Injector) {
          if (AppInjector) {
              // Should not happen
              console.error('Programming error: AppInjector was already set');
          }
          else {
              AppInjector = injector;
          }
      }
      

      接下来,在您的AppModule 中,使用:

      import {Injector} from '@angular/core';
      import {setAppInjector} from './app-injector';
      
      export class AppModule {
          constructor(injector: Injector) {
              setAppInjector(injector);
          }
      }
      

      在需要的地方,使用:

      import {AppInjector} from './app-injector';
      const myService = AppInjector.get(MyService);
      

      【讨论】:

      • 这个最初的var injector = ReflectiveInjector.resolveAndCreate([AppService); var appAlertService = injector.get(AppService); 不起作用,因为我的AppService 注入了ngrx Store 并抛出了no Store provider found,所以AppInjector.get(AppService); 一切正常。任何想法为什么?
      • @Kuncevic,我不知道。但要确定的是:您的原始版本正在创建AppService 的新实例,不与可能也使用它的其他组件共享(而上面的解决方案获得了一个共享单例)。我仍然希望您新创建的实例能够正确注入它需要的任何共享依赖项,但显然不是。
      • 这太棒了。解决了我所有的问题
      • @Arjan 嗨,我收到:“未捕获的类型错误:无法读取未定义的属性 'get'”,我按照您的要求做了所有事情
      • @Arjan 即使在此之后我也得到了未定义的服务。
      【解决方案3】:

      angular 2.0.0 final 的另一种解决方案:

      platformBrowserDynamic().bootstrapModule(AppModule, [
        {
          defaultEncapsulation: ViewEncapsulation.Emulated,
          providers: [
            { provide: TRANSLATIONS, useValue: TRANSLATION },
            { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
            { provide: LOCALE_ID, useValue: 'fr' }
          ]
        }
      ]).then((modref: NgModuleRef<any>) => {
        appInjector(modref.injector);
      });
      

      【讨论】:

      • 你确定这行得通吗?因为组件在引导期间执行并且注入器在组件之后工作,所以给我留下了 null ServiceLocator.instance?
      • @dstr,我在我的应用程序中使用了这段代码,它可以工作。您使用的是哪个角度版本?你能过去一份错误堆栈跟踪的副本吗? (对不起我的英语不好!)
      • 你能解释一下它是如何工作的吗?我可以在这一步中从 Window 中读取配置对象并注入到 Angular 中吗?
      【解决方案4】:

      我已经设法使用手动助推器来做到这一点。不要在@NgModule 中使用“bootstrap: [AppComponent]”声明,而是使用ngDoBootstrap 方法:

      export class AppModule {
          constructor(private injector: Injector) {
          }
      
          ngDoBootstrap(applicationRef: ApplicationRef) {
              ServiceLocator.injector = this.injector;
              applicationRef.bootstrap(AppComponent);
          }
      }
      

      【讨论】:

      • 为什么不在 AppModule 的构造函数中分配 bootstrap: [AppComponent] 而不使用 ngDoBootstrap?或者是否有可能在引导后调用 AppModule 的构造函数?
      • @PetrMarek:我不太记得了,但我认为您只能在 ngDoBootstrap 事件中获得 ApplicationRef。
      • 我将 Injector 的引用存储在 AppModule 构造函数中,它似乎工作正常。 (不要使用 ngDoBootstrap)
      猜你喜欢
      • 2017-04-16
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      相关资源
      最近更新 更多