[Fixed] Provide service in lazy loaded module

Issue

A project is importing module A singleton statically (with forRoot) in the app/root module which contains a service which is using a provided service injection token.

const providedChildServices: ChildService[] = this._injector.get(ProvidedByChildService, []); //inside the root service

This ProvidedByChildService is provided by a module B which is lazy loaded when navigating inside the app.

This behaviour occurs: users is navigating inside app, goes inside route for B module –> everything of module B is lazy loaded –> RootService requests provided ‘ProvidedByChildService’ but can’t find it. Is this architecture possible? It works when I register ProvidedByChildService as a provider in the A module (instead of B).

Solution

No, this is not possible. It isn’t the right architectural choice that a root service depends on a child service.

If a root service depends on a subsequent service, that needs to be in the root as well.

You did not specify reason in why you need to do it. But in the scenario you provided, you do not save bytes of the root bundle, because the child service is already referenced there in the root service, therefore will be bundled with it.

As of why your code does not work – the _injector in the root service is the root injector and therefore it does not try to resolve the module by looking into child modules. In angular, loaded modules create a provider tree in which child injectors traverse the tree to the root until they find the provider they look for – not the other way around.

I provide some possible solutions:

  1. You move the currently child service into the root.
  2. You move the parts of the root service, that are dependent on the child service into a new child service which will be provided in the child module.
  3. You mark the child service as a @Optional dependency of the root module and add a provider of the root services into the child module providers array.

Leave a Reply

(*) Required, Your email will not be published