2017-09-04 145 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