Storing injector instance for use in components

For today’s TypeScript and Angular 5, avoiding WARNING in Circular dependency detected when importing the global injector, first declare a helper, e.g. 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;
    }
}

Next, in your AppModule, set it using:

import {Injector} from '@angular/core';
import {setAppInjector} from './app-injector';

export class AppModule {
    constructor(injector: Injector) {
        setAppInjector(injector);
    }
}

And wherever needed, use:

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)