Getting instance of service without constructor injection

前端 未结 4 1864
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 05:21

I have a @Injectable service defined in bootstrap. I want to get the instance of the service without using constructor injection. I tried using Reflective

4条回答
  •  醉话见心
    2020-11-28 06:14

    In the updated Angular where ngModules are used, you can create a variable available anywhere in the code:

    export let AppInjector: Injector;
    
    export class AppModule {
      constructor(private injector: Injector) {
        AppInjector = this.injector;
      }
    }
    

    Now, you can use the AppInjector to find any service in anywhere of your code.

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

提交回复
热议问题