2017-11-24 4 views
2

対Injector.resolveAndCreate NG2使用するとき、私はこのarticleを読み、角度2で依存性注入に関するこれらのビデオを見ました:
活字体のコンストラクタ

そしてAngularのDIについてはかなり理解しています。しかし、私はそれを正しく使う方法を混同しています。

型定義を使用するとき、私の質問は、(1)このようなものです:

import { Component } from '@angular/core'; 
import { Http } from '@angular/http'; 
@Component({ 
    selector: 'example-component', 
    template: '<div>I am a component</div>' 
}) 
class ExampleComponent { 
    constructor(private http: Http) {} 
} 

、いつInjectorを使用する(2)このように:

import { Injector, provide } from 'angular2/core' 
var injector = Injector.resolveAndCreate(
[ 
provide(SomeObj, {useClass: SomeObj}) 
]); 

二つとして、私は混乱してしまいます私はそれがどこに行くべきであるか分からない(コンポーネント、サービス、または他の?)、それを消費する方法?注意すべき

答えて

1

まず最初はresolveAndCreate方法は、このようなReflectiveInjector(ないInjector)で呼び出されていることである。

import { ReflectiveInjector } from '@angular/core'; 
const customInjector = ReflectiveInjector.resolveAndCreate(...) 

2つ目はReflectiveInjectorStaticInjectorの非推奨されていることです。私はよく分からないよう

import { HttpClient } from '@angular/common/http'; 
const customInjector = new StaticInjector([ 
    {provide: `MyCustomToken`, useValue: 'just a string value', deps: [HttpClient]} 
]) 

秒1は私が混乱してしまいます。だから今は、カスタムインジェクタを作成したい場合は、StaticInjectorを使用する必要があり、このように行うことができますAngular deprecates ReflectiveInjector and introduces StaticInjector. Should you care?

でそれについての詳細を読みますそれは になっていますどこ

カスタムインジェクタがそれらをインスタンス化する際に、モジュールまたはコンポーネント工場のいずれかに渡すことができ、反射または静的のいずれか注射器を使用して作成して行きます。ここでは記事Here is what you need to know about dynamic components in Angularからのいくつかの例は以下のとおりです。

const customInjector = new StaticInjector(...); 

// module 
this.loader.load('app/t.module#TModule').then((klass) => { 
const factory = compiler.compileModuleSync(klass); 
const module = factory.create(customInjector); 

// dynamic component 
const r = module.componentFactoryResolver; 
const cmpFactory = r.resolveComponentFactory(AComponent); 
const componentRef = cmpFactory.create(customInjector); 
+0

(2)、私は 'のconst customInjector =新しいStaticInjector([...])を持つすべてのクラスを宣言することによって、カスタムインジェクターを作成する必要がありますと;' 1つのファイルに例えば: 'DIProvider.ts'を実行し、必要な場所であればそれを消費します。例えば、' var someObj = customInjector.get(SomeObj); 'これは? – hngdev

+0

@hngdev、あなたはどんなファイルでもインジェクタで作成することができますが、おそらくそこに必要な場所 –