2017-09-04 9 views
2

私の角型アプリケーションでは、私は、インジェクタを返すAppInjectorと呼ばれるグローバル変数があります。この変数はAppModuleに設定されています。角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 ... 
     )); 
} 

問題は角コンパイラが原因AppInjectorの循環依存(WARNING 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について私に警告していることである

私はこの警告を取り除くことができますどのように 私がいることを知っていますこの場合、私はinitNodeTemplate()にパラメータとしてdetailServiceを渡すことができましたので、私はもうAppInjectorを必要としません。しかし、私は自分の機能をうんざりさせたくありませんこのサービスのパラメータ。

+0

サイクルを解除します。それを引き起こすコードを見ずにどうやって正確に伝えるのは難しいです。 https://stackoverflow.com/questions/41585863/angular2-injecting-services-in-custom-errorhandler/41585902#41585902 –

答えて

1

これを避ける簡単な方法は、あなたのクラスにAppInjectorをインポートして、それらのクラスを宣言または提供するAppModuleと異なるものからインポートさせることです。

ですから、ヘルパーを追加してください。 app-injector.ts

あなた AppModule、使用中の
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; 
    } 
} 

そして:

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

関連する問題