如何将提供者注入组件?

时间:2016-04-05 10:40:03

标签: angular

如何将提供者注入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?

1 个答案:

答案 0 :(得分: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

如果您想了解有关分层注射器的更多信息,可以查看以下问题: