存储注入器实例以用于组件

dst*_*str 23 angular

在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)

  • @Kuncevic,我不知道。但是要确保:您的原始版本正在创建一个新的AppService实例,不与可能也会使用它的其他组件共享(而上述解决方案是一个共享的单例)。我仍然希望您新创建的实例能够正确注入所需的任何共享依赖关系,但显然不是。 (2认同)
  • 这太棒了。解决了我所有的问题 (2认同)

dst*_*str 9

我已经设法使用手动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)

  • 我在AppModule构造函数中存储Injector的引用,它似乎工作正常.(不要使用ngDoBootstrap) (3认同)