2016-07-12 35 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

我的意思是,为什么你不能在儿童的构造函数中包含该服务? –