角度2:全局AppInjector。如何避免警告“循环依赖”

Ros*_*eur 2 typescript angular

在我的Angular App中,我有一个名为AppInjector的全局变量,该变量返回Injector。该变量ist设置在中AppModule

export let AppInjector: Injector;

@NgModule({
    declarations: [
        AppComponent,
    ],
    bootstrap: [AppComponent],
})
export class AppModule {

    constructor(private injector: Injector) {
        AppInjector = this.injector;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一些辅助功能,可以通过AppInjector特殊服务获得帮助。辅助函数位于单独的文件中,不属于任何组件。例如:

function initNodeTemplate() {

    diagram.nodeTemplateMap.add(NodeCategory.Question,
        GO(go.Node, "Auto",
            {
                click: (evt, obj) => {(AppInjector.get(MyService) as MyService).myFunction(obj)},
            },
            // other stuff ...
        ));
}
Run Code Online (Sandbox Code Playgroud)

问题是,该角的编译器警告我关于循环依赖(因为AppInjectorWARNING in Circular dependency detected: src\app\app.module.ts -> src\app\frame\frame.module.ts -> src\app\designer\designer.module.ts -> src\app\designer\designer.component.ts -> src\app\designer\helpers\templates.helper.ts -> src\app\app.module.ts

我如何摆脱这个警告? 我知道我可以将服务注入组件,然后将服务传递给助手功能。在这种情况下,我可以将其detailService作为参数传递给initNodeTemplate(),因此不再需要AppInjector了。但我想避免将此服务的功能参数弄乱。

Arj*_*jan 5

避免这种情况的一种简单方法是让您的类AppInjector从不同于AppModule声明/提供那些类的导入。

因此,添加一个助手,例如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 access the exported {@link AppInjector}, needed as ES6 modules export
 * immutable bindings; see http://2ality.com/2015/07/es6-module-exports.html
 */
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)

(不需要手动强制转换结果;编译器应该知道您的服务类型。)