-2

I am loading module dynamically using system JS in Angular 6 and using angular-cli very similar to below link.

(Load new modules dynamically in run-time with Angular CLI & Angular 5)

Dynamically loaded module creates it's child injector and create new instance of services rather than using services from root injector.

As per Angular doc, lazy loaded module creates its own child injector and instances of service. In order to avoid that (for singleton), they suggest to create forRoot static method in lazy loaded module and import it in app module.

But in my case, as I am loading module at run time, I can't import LazyLoadedMOdule.forRoot() at bootstrap. I get to know which module is going to get loaded only at run time.

Can you please suggest to keep services singleton and use it in dynamically loaded module ?

Chetan
  • 11
  • 1

1 Answers1

0

For services that need to be singletons throughout the entire app, the recommended approach is to define those in a core module, which is then imported in the root module (AppModule).

You can refer to the Angular Style Guide for more detailed information.

Axel Zarate
  • 466
  • 4
  • 14
  • this can be done but problem here is that lazy loaded module always creates separate child injector with new service instance . only way to deal with it is import static method forRoot in main app which is not possible in my case – Chetan Mar 05 '19 at 18:43
  • Make sure you are not re-registering those services inside your lazy-loaded module definition. In other words, they should be declared _only_ in the `providers` section of the core module. – Axel Zarate Mar 05 '19 at 19:37