Access to the root Angular 2 injector instance worldwide

How to access an instance of the root Angular 2 injector worldwide (say, from the browser console).

In Angular 1, this was angular.element(document).injector() .

During testing and research, it may be useful to use the browser console to get an injector, and then access instances of different components, directives, services, etc.

+6
source share
2 answers

You must install it in the service after the initial loading of the application:

 export var applicationInjector: Injector; bootstrap([AppComponent]).then((componentRef: ComponentRef) => { applicationInjector = componentRef.injector; }); 

Then you can import it into other parts of the application:

 import {applicationInjector} from './bootstrap'; 

See this question for more information:

Edit

You can embed ApplicationRef into components and have access to the root injector through it:

 @Component({ (...) }) export class SomeComponent { constructor(private app:ApplicationRef) { var rootInjector = app.injector; } } 

You need to use a dependency injection to get it.

+9
source

In Angular v.4.xx root injector is on PlatformRef . You can access it as follows:

 import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; // create a platform let platform = platformBrowserDynamic(); // save reference to the global object window['rootInjector'] = platform.injector; // boostrap application platform.bootstrapModule(AppModule); 

Or inside any such component:

 export class AppComponent { constructor(platform: PlatformRef) { console.log(platform.injector); 

But the root injector is pretty useless. It contains mainly data and compiler and platform helpers:

 [ "InjectionToken Platform ID", "PlatformRef_", "PlatformRef", "Reflector", "ReflectorReader", "TestabilityRegistry", "Console", "InjectionToken compilerOptions", "CompilerFactory", "InjectionToken Platform Initializer", "PlatformLocation", "InjectionToken DocumentToken", "InjectionToken Platform: browserDynamic", "InjectionToken Platform: coreDynamic", "InjectionToken Platform: core" ] 

You are probably looking for an AppModule injector, which you can do this:

 platform.bootstrapModule(AppModule).then((module) => { window['rootInjector'] = module.injector; }); 

You can extract ApplicationRef or root ComponentRef from it:

 platform.bootstrapModule(AppModule).then((module) => { let applicationRef = module.injector.get(ApplicationRef); let rootComponentRef = applicationRef.components[0]; }); 

In addition, if Angular is running in development mode, you can get either an AppModule or a lazy loaded NgModule injector, for example:

 ng.probe($0).injector.view.root.ngModule 
+4
source

All Articles