Can a service defined on a module inject a service defined on a component declared by the same module

669 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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) { ... }
0
On

Providers are looked up from the component where they are required. If not found provider search continues at the parent until the root injector (providers added to @NgModule(...) of non-lazy loaded modules ) is reached.

This means your service provided at the module can't inject a service provided by a component, because it would require from the root injector to search towards the leafs, which won't happen. Only the other way around works. Dependencies need to be provided at the same or a higher level.