2017-09-04 141 views
2

在我的Angular应用程序中,我有一个名为AppInjector的全局变量,它返回Injector。该变量ist在AppModule中设置。Angular 2:全局AppInjector。如何避免警告“循环依赖”

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 ... 
     )); 
} 

的问题是,该角的编译器警告我关于循环依赖(因为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了,但是我想避免搞乱我的功能参数与这个服务。

+0

打破循环。很难确切地知道如何查看导致它的代码。另见https://stackoverflow.com/questions/41585863/angular2-injecting-services-in-custom-errorhandler/41585902#41585902 –

回答

1

避免这种情况的一种简单方法是让您的课程从不同于AppModule的东西导入AppInjector来声明/提供这些非常类。

因此,添加助手,例如, 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; 
    } 
} 

,然后在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); 

(应该没有必要用于手动输出结果;编译器应该知道您的服务的类型。)

+0

感谢您的回答。这对我不起作用。仍然得到相同的错误:( –

+0

然后,我猜这个错误不是(或不再)与使用全局'AppInjector'有关,或者你没有在组件中删除'AppModule'现在已经过时的导入。错误真的完全一样? – Arjan

+0

它工作完美!谢谢 – nim4n