Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度2:全局AppInjector。“如何避免警告”;循环依赖性“;_Angular_Typescript - Fatal编程技术网

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

Angular 角度2:全局AppInjector。“如何避免警告”;循环依赖性“;,angular,typescript,Angular,Typescript,在我的Angular应用程序中,我有一个名为AppInjector的全局变量,它返回喷油器。此变量在AppModule中设置 export let AppInjector: Injector; @NgModule({ declarations: [ AppComponent, ], bootstrap: [AppComponent], }) export class AppModule { constructor(private injecto

在我的Angular应用程序中,我有一个名为AppInjector的全局变量,它返回喷油器。此变量在
AppModule
中设置

export let AppInjector: Injector;

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

    constructor(private injector: Injector) {
        AppInjector = this.injector;
    }
}
我有一些助手函数,它们是在
AppInjector
特殊服务的帮助下获得的。助手函数位于单独的文件中,不属于任何组件。例如:

function initNodeTemplate() {

    diagram.nodeTemplateMap.add(NodeCategory.Question,
        GO(go.Node, "Auto",
            {
                click: (evt, obj) => {(AppInjector.get(MyService) as MyService).myFunction(obj)},
            },
            // other stuff ...
        ));
}
问题是Angular编译器警告我循环依赖关系(因为检测到循环依赖关系中的
AppInjector
警告:
src\app\app.module.ts->src\app\frame\frame.module.ts->src\app\designer\designer.module.ts->src\app\designer\component.ts->src\app\helpers\templates.helper.ts->src\app\app\app.module.ts

我如何摆脱此警告?
我知道我可以将服务注入组件,然后将服务传递给helper函数。在这种情况下,我可以将
detailService
作为参数传递给
initNodeTemplate()
因此我不再需要
AppInjector
。但我希望避免将我的函数参数与此服务混淆。

避免这种情况的一个简单方法是让您的类从声明/提供这些类的
AppModule
之外的其他对象导入
AppInjector

因此,添加一个助手,例如
app injector.ts

从'@angular/core'导入{Injector};
/**
*允许使用'AppInjector.get(MyService)`(而
*`ReflectiveInjector.resolveAndCreate(MyService)`将创建一个新实例
*(服务范围)。
*/
export-let-AppInjector:Injector;
/**
*用于访问导出的{@link AppInjector}的帮助程序,ES6模块导出时需要该帮助程序
*不可变绑定;请参见http://2ality.com/2015/07/es6-module-exports.html
*/
导出功能setAppInjector(喷油器:喷油器){
如果(AppInjector){
//不应该发生
错误('编程错误:AppInjector已设置');
}
否则{
AppInjector=喷油器;
}
}
然后在
AppModule
中,使用:

从'@angular/core'导入{Injector};
从“/app injector”导入{setAppInjector};
导出类AppModule{
建造师(注入器:注入器){
setAppInjector(喷油器);
}
}
…在其他类中,仍使用:

从“/app injector”导入{AppInjector};
constmyservice=AppInjector.get(myService);

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

打破这个循环。如果没有看到导致它的代码,很难准确地说出是如何产生的。另请参阅,谢谢您的回答。这对我不起作用。仍然会出现相同的错误:(那么我猜错误不是(或者不再是)与使用全局
AppInjector
相关,或者您未能删除组件中现已过时的
AppModule
导入。错误是否真的完全相同?这就是我一直在寻找的解决方案。但是,我现在正努力使测试正常运行,因为检索服务的基类返回null对于HtppClient。