在RC5之前我使用appref injector作为服务定位器,如下所示:
Startup.ts
bootstrap(...)
.then((appRef: any) => {
ServiceLocator.injector = appRef.injector;
});
Run Code Online (Sandbox Code Playgroud)
ServiceLocator.ts
export class ServiceLocator {
static injector: Injector;
}
Run Code Online (Sandbox Code Playgroud)
组件:
let myServiceInstance = <MyService>ServiceLocator.injector.get(MyService)
Run Code Online (Sandbox Code Playgroud)
现在在bootstrapModule()中执行相同操作.然后()不起作用,因为组件似乎在promise之前开始执行.
有没有办法在组件加载之前存储喷油器实例?
我不想因为我使用其中的许多组件衍生,我宁可不注射器注入到所有这些基本成分的注射器使用构造器注入.
Arj*_*jan 38
对于今天的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;
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,在您的AppModule设置中使用:
import {Injector} from '@angular/core';
import {setAppInjector} from './app-injector';
export class AppModule {
constructor(injector: Injector) {
setAppInjector(injector);
}
}
Run Code Online (Sandbox Code Playgroud)
并在需要的地方使用:
import {AppInjector} from './app-injector';
const myService = AppInjector.get(MyService);
Run Code Online (Sandbox Code Playgroud)
我已经设法使用手动boostrapping.不要使用" bootstrap: [AppComponent]"声明@NgModule,ngDoBootstrap而是使用方法:
export class AppModule {
constructor(private injector: Injector) {
}
ngDoBootstrap(applicationRef: ApplicationRef) {
ServiceLocator.injector = this.injector;
applicationRef.bootstrap(AppComponent);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9587 次 |
| 最近记录: |