我有一个主要组件,它有 2 个子组件和一个服务。我确实bootstrap(Main, [MyService])
,但是我希望从这两个子组件中获得功能(可以调用服务函数)。我应该如何将此服务的一个实例从父组件传递到我的子组件?
不要在组件中指定服务的提供者,只需将其包含在构造函数中即可。
如果您在引导程序中提供服务并希望它是单一实例,则组件将如下所示。
@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) {
}
}