2016-07-12 28 views

回答

0

不要在組件中指定服務的提供者,只要將其包含在構造函數中即可。

如果您在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) { 
 
    } 
 
}

+0

我這樣做。在主要組件中,我可以在構造函數中包含提供程序,但在子組件中,我不能,我有一個錯誤。也許我應該將父組件的提供者以某種方式傳遞給子組件? –

+0

什麼錯誤?不應該有必要傳遞任何東西 –

+0

我的意思是,爲什麼你不能在兒童的構造函數中包含該服務? –