0
我有主要组件有2个子组件和一个服务。我做bootstrap(Main, [MyService])
,但我想从这些两个子组件都具有功能(可能调用服务功能)。我应该如何将这个服务的一个实例从父组件传递给我的子组件?将全球服务传递给Angular 2中的子类12
我有主要组件有2个子组件和一个服务。我做bootstrap(Main, [MyService])
,但我想从这些两个子组件都具有功能(可能调用服务功能)。我应该如何将这个服务的一个实例从父组件传递给我的子组件?将全球服务传递给Angular 2中的子类12
不要在组件中指定服务的提供者,只要将其包含在构造函数中即可。
如果您在bootstrap中提供服务并希望它是单身人士,您的组件将如下所示。
@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) {
}
}
我这样做。在主要组件中,我可以在构造函数中包含提供程序,但在子组件中,我不能,我有一个错误。也许我应该将父组件的提供者以某种方式传递给子组件? –
什么错误?不应该有必要传递任何东西 –
我的意思是,为什么你不能在儿童的构造函数中包含该服务? –