2016-04-05 41 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" 
    } 

    ... 
} 

如何注入到爲MyService MyFormDetailComponent?

+0

EUH,你不把它注射了嗎? ;-) –

+0

或者你的意思是進入MyFormComponent而不是MyFormDetailComponent? –

+0

目前的行爲是什麼?任何錯誤消息? 「MyService」的外觀如何? –

回答

1

如果要將相同的服務注入到兩個組件中,只需將MyService定義爲父組件的providers屬性即可。這樣,(因爲分層噴射器),你將能夠把它注入到這兩個組件:

@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:https://plnkr.co/edit/rUBgioLtqIAfWNCkRnlN?p=preview

如果你想知道更多關於分層噴射器,你可以看一下這個問題:

相關問題