Storing injector instance for use in components

前端 未结 4 1613
一向
一向 2020-11-27 16:51

Before RC5 I was using appref injector as a service locator like this:

Startup.ts

bootstrap(...)
.then((appRef: any) => {
    ServiceLocator.injec         


        
4条回答
  •  春和景丽
    2020-11-27 16:57

    Class based solution.

    Often I need to refer to a service from classes that are used by other classes. Injecting services via a constructor is cumbersome and causes issues for the calling classes, which do not need the given service(s).

    In Angular 8, I setup a library class: ServiceInjectorModule (can also be used inside sub-modules)

    (derived from similar answers on stackoverflow)

    File: 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;
      }
    }
    

    File: my-lib.module.ts

    Note: You can skip this library module as it is only more convenient if you have other services or modules to use. If you skip it, import ServiceInjectorModule directly to your AppModule.

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

    Import MyLibModule to your AppModule or where best fits.

    Now in your components or classes, simply:

    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(...
      }
    
    }
    

提交回复
热议问题