全局访问根Angular 2注入器实例

Iva*_*van 9 dependency-injection angular

如何全局访问根Angular 2注入器的实例(例如,从浏览器控制台).

在Angular 1中它是angular.element(document).injector().

它在测试和探索过程中非常有用,可以使用浏览器控制台获取注入器,然后访问不同组件,指令,服务等的实例.

Thi*_*ier 14

在引导应用程序后,您必须将其设置为服务:

export var applicationInjector: Injector;

bootstrap([AppComponent]).then((componentRef: ComponentRef) => {
  applicationInjector = componentRef.injector;
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其导入应用程序的其他部分:

import {applicationInjector} from './bootstrap';
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此问题:

编辑

您可以注入ApplicationRef组件并通过它访问根注入器:

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

您需要利用依赖注入来获取它.

  • 在当前的Angular(2.4.4)```ApplicationRef```中没有公共属性```injector```; 显然它是私人的. (3认同)

Max*_*kyi 12

在Angular中v.4.x.x,根注入器位于PlatformRef上.您可以像这样访问它:

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);
Run Code Online (Sandbox Code Playgroud)

或者在这样的任何组件内:

export class AppComponent {
  constructor(platform: PlatformRef) {
      console.log(platform.injector);
Run Code Online (Sandbox Code Playgroud)

但是root注射器很没用.它主要包含编译器和平台特定的数据和帮助程序:

[
  "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"
]
Run Code Online (Sandbox Code Playgroud)

您可能正在寻找AppModule能够像这样得到的喷射器:

platform.bootstrapModule(AppModule).then((module) => {
  window['rootInjector'] = module.injector;
});
Run Code Online (Sandbox Code Playgroud)

您可以从中提取ApplicationRef或根ComponentRef:

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

此外,如果Angular在开发模式下运行,您可以获得AppModule或延迟加载的NgModule注入器,如下所示:

ng.probe($0).injector.view.root.ngModule
Run Code Online (Sandbox Code Playgroud)

  • `ng.probe($ 0).injector.view.root.ngModule`这样你可以得到'AppModule`或延迟加载的`NgModule`注入器 (3认同)