Can a service defined on a module 'my' inject a service defined on a component declared by the module 'my'?
I've tested and it seems to be the case, so this question is mostly for the confirmation. So, I have this component that defines ComboFeatureService
:
@Component({
selector: 'combo-feature',
providers: [ComboFeatureService],
template: '<div>I am feature</div>'
})
export class ComboFeature {
constructor(comboService: ComboService) {
comboService.report();
}
}
Then I have a service that depends on ComboFeatureService
:
@Injectable()
export class ComboService {
constructor(public comboFeature: ComboFeatureService) {
}
And both the component and the service are defined on the same module:
@NgModule({
providers: [ComboService],
declarations: [ComboFeature],
exports: [ComboFeature]
})
export class ComboModule {
Is my understanding correct that even they are both defined on the same module, ComboService
won't be able to access to ComboFeatureService
?
If that's the case, then as I understand component injector is not a child of root injector, correct?
It doesn't matter if the services are defined on the same module or not (unless this is lazy loaded module), module providers
belong to root injector.
In order to do that, both providers should be defined on current injector:
@Component({
...
providers: [ComboService, ComboFeatureService]
})
export class ComboFeature {
constructor(comboService: ComboService) { ... }
Alternatively, ComboFeatureService
can be injected as optional, this will allow ComboService
to use ComboFeatureService
from current injector (or nothing if there is none):
@Injectable()
export class ComboService {
constructor(Optional() public comboFeature: ComboFeatureService) { ... }