存储注射器实例以用于组件
在RC5之前,我使用appref注入器作为服务定位器,如下所示:
Startup.ts
bootstrap(...) .then((appRef: any) => { ServiceLocator.injector = appRef.injector; });
ServiceLocator.ts
export class ServiceLocator { static injector: Injector; }
组件:
let myServiceInstance = <MyService>ServiceLocator.injector.get(MyService)
现在在bootstrapModule()中做同样的事情,然后()不起作用,因为组件似乎开始在承诺之前执行。
是否有一种方法来存储组件加载之前的注入器实例?
我不想使用构造函数注入,因为我在一个由许多组件派生的基本组件中使用注入器,而不是将注入器注入到所有组件中。
我已经设法使用手动增压。 不要在@NgModule
使用“ bootstrap: [AppComponent]
”声明,而@NgModule
使用ngDoBootstrap
方法:
export class AppModule { constructor(private injector: Injector) { } ngDoBootstrap(applicationRef: ApplicationRef) { ServiceLocator.injector = this.injector; applicationRef.bootstrap(AppComponent); } }
对于今天的TypeScript和Angular 5,在导入全局注入器时避免WARNING in Circular dependency detected
,首先声明一个帮助器,例如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; } }
接下来,在您的AppModule
,使用以下AppModule
设置它:
import {Injector} from '@angular/core'; import {setAppInjector} from './app-injector'; export class AppModule { constructor(injector: Injector) { setAppInjector(injector); } }
并在需要的地方使用:
import {AppInjector} from './app-injector'; const myService = AppInjector.get(MyService);
另一个angular度为2.0.0的解决scheme:
platformBrowserDynamic().bootstrapModule(AppModule, [ { defaultEncapsulation: ViewEncapsulation.Emulated, providers: [ { provide: TRANSLATIONS, useValue: TRANSLATION }, { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }, { provide: LOCALE_ID, useValue: 'fr' } ] } ]).then((modref: NgModuleRef<any>) => { appInjector(modref.injector); });