简体   繁体   中英

Angular 4.4.6 shared services in lazy loaded modules

I am googling about a 2 weeks now but cannot find any suitable answer to my question. So I am asking here.

Description

Tools: Angular 4.4.6 and Angular-CLI 1.4.9

I have fairly simple application that I am working on. It has AuthModule, AdminModule, LayoutModule and SharedModule. Everything works fine if I add all of these modules to the AppModule but, the issue is when I add these modules too the the AppModule then my vender.... size goes way more then 600kb (--aot).

Explanation of modules.

ShareModule : has some models and services that are common to each module eg HttpService . AuthModule: contains simple Login and Register components that uses HttpService from shared module

So I decided to put them all as lazy loaded modules with routing which is described here . This reduces the size of vendor...js by almost 50% but then then dependencies doesn't work.

Although I referenced SharedModule in LazyLoaded module but still that doesn't solve the issue, dependencies doesn't work. I know, each lazy loaded module creates its own DI tree but it doesn't resolve dependencies other than that has been created and provided inside the lazy loaded module.

As I said in tools section I am using Angular-CLI which has an awesome feature of detecting similar module used twice in some components if so then it creates a common...js for that module. But still issue remains I cannot access the shared service in lazy loaded module.

Is there a possibility or can anyone point me how to load shared services in lazy loaded modules?

Thanks

If you want services from lazy loaded modules to be available as global singletons and available everywhere, implement forRoot and import MyLazyModule.forRoot() in AppModule . This way the providers are registered globally, while the rest is lazy loaded.

See https://angular.io/guide/ngmodule#configure-core-services-with-coremoduleforroot for more details.

I have found the solution. Which is mentioned in agular documentation just didn't get my attention before.

Do not specify app-wide singleton providers in a shared module. A lazy-loaded module that imports that shared module makes its own copy of the service.

What you need to do is do not provide and service from shared module. Just import shared module in lazy loaded module and provide the service from that lazy loaded module.

I hope this will help someone else.

Happy coding. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM