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) {
}
}
我這樣做。在主要組件中,我可以在構造函數中包含提供程序,但在子組件中,我不能,我有一個錯誤。也許我應該將父組件的提供者以某種方式傳遞給子組件? –
什麼錯誤?不應該有必要傳遞任何東西 –
我的意思是,爲什麼你不能在兒童的構造函數中包含該服務? –