angularangular2-di

Does lazy module create child injector of a root injector


Suppose I have the following LazyModule that is lazily loaded and the LazyComponent declared inside of it:

@NgModule({
    declarations: [LazyComponent],
    providers: [LazyModuleService],
})
export class LazyModule { ...


@Component({
    selector: 'my-lazy',
    providers: [LazyComponentService]
})
export class LazyComponent { ...

My understanding is that when loading LazyModule angular will create a child injector for this module from rootInjector, something like this:

var lazyModuleInjector = rootInjector.resolveAndCreateChild([LazyModuleService]);

and then create a child injector for LazyComponent like this:

var lazyModuleInjector = lazyModuleInjector.resolveAndCreateChild([LazyComponentService]);

So eventually the injector tree be like this:

enter image description here

Is it correct?


Solution

  • Yes, this is correct. This wasn't done intentional but because an injector is readonly after it was created. Because lazy loaded modules are loaded later, its providers can't be added to the application root provider, because this one is already sealed. This is why they introduced a new root scope for lazy loaded modules.

    If you want global providers (singletons) of providers provided by lazy loaded modules, implement forRoot() in the lazy loaded module and provide the global providers there, and then import only the providers into the application root scope with imports: [LazyModule.forRoot()].