我的主要组件有2个子组件和服务。我做var myInt: 13 = int(enteredAge)
,但是我希望从这两个子组件中获得功能(可以调用服务功能)。我应该如何将此服务的一个实例从父组件传递到我的子组件?
答案 0 :(得分: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) {
}
}