Getting instance of service without constructor injection

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

Add this code in app.module.ts

import { Injector, NgModule } from '@angular/core';

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);

Leave a Comment