2016-04-05 6 views
0

Angular2のコンテナコンポーネントにプロバイダを挿入するにはどうすればよいですか?例えばプロバイダをコンポーネントに挿入する方法は?

私は親コンポーネントを持つ:

@Component({ 
    selector: 'myForm', 
    template: '<form><myForm-detail></myForm-detail></form>', 
    directives: [ MyFormDetailComponent ] 
}) 
export class MyFormComponent { 
    ... 
} 

とコンテナコンポーネント:

@Component({ 
    selector: 'myForm-detail', 
    template: '<input type="text">', 
    providers: [ MyService ] 
}) 
export class MyFormDetailComponent { 
    constructor(s: MyService) { 
     console.log(s); // return "undefined" 
    } 

    ... 
} 

MyFormDetailComponentにMyServiceでを注入する方法は?

+0

EUHが、あなたはまだそれを注入しないでください:

あなたは、階層インジェクタについての詳細をお知りになりたい場合は、この質問を見ているだろうか? ;-) –

+0

MyFormComponentではなくMyFormComponentを意味しますか? –

+0

現在の動作は何ですか?エラーメッセージはありますか? 'MyService'はどのように見えますか? –

答えて

1

両方のコンポーネントに同じサービスを注入する場合は、親コンポーネントのproviders属性にMyServiceを定義するだけです。この方法(およびため、階層のインジェクタ)は、次の2つのコンポーネントにそれを注入することができるようになります:https://plnkr.co/edit/rUBgioLtqIAfWNCkRnlN?p=preview

@Component({ 
    selector: 'myForm', 
    template: '<form><myForm-detail></myForm-detail></form>', 
    directives: [ MyFormDetailComponent ], 
    providers: [ MyService ] 
}) 
export class MyFormComponent { 
    constructor(s: MyService) { 
    } 
    ... 
} 

(...) 

@Component({ 
    selector: 'myForm-detail', 
    template: '<input type="text">', 
}) 
export class MyFormDetailComponent { 
    constructor(s: MyService) { 
    console.log(s); 
    } 
} 

このplunkrを参照してください。

関連する問題