2016-07-12 5 views
0

私は2つの子コンポーネントとサービスを持つメインコンポーネントを持っています。私はbootstrap(Main, [MyService])をやっていますが、これらの両方の子コンポーネントから機能(サービス機能を呼び出す可能性)を持ちたいと思います。このサービスのインスタンスを親コンポーネントから子コンポーネントにどのように渡す必要がありますか?グローバルサービスをアングル2の子クラスに渡す

答えて

0

コンポーネントにサービスのプロバイダを指定しないでください。コンポーネントをコンストラクタに含めるだけです。

サービスをブートストラップに提供していて、それをシングルトンにしたい場合、コンポーネントは次のようになります。

@Component({ 
 
    template: '<child-component></child-component>', 
 
    directives: [ChildComponent], 
 
    providers: [] // no need to include the specify the service here 
 
}) 
 

 
export class MyComponent { 
 
    /*even though you're injecting the service here, it will use the same 
 
    instance provided in the bootstrap */ 
 

 
    constructor(private myService: MyService) { 
 
    
 
    } 
 
}

@Component({ 
 
    selector: 'child-component', 
 
    providers: [] // no need to include the specify the service here 
 
}) 
 

 
export class ChildComponent { 
 
    //you can do this as long as you don't specify the service in the providers list 
 
    constructor(private myService: MyService) { 
 
    } 
 
}

+0

私はそれを行います。主なコンポーネントでは、コンストラクタにプロバイダを含めることはできますが、子コンポーネントではできません。エラーがあります。たぶん私は何らかの方法で親コンポーネントから子コンポーネントにプロバイダを渡す必要がありますか? –

+0

どのようなエラーが報告されましたか? –

+0

私は、子供のコンストラクタにこのサービスを含めることができないのはなぜですか? –

関連する問題