Angular: Lazy loading modules with services

后端 未结 5 1147
耶瑟儿~
耶瑟儿~ 2021-02-01 04:47

I\'ve been following this tutorial, to understand lazy loading, and below is my inference.

Scenario 1: Services are provided by putting them in the

5条回答
  •  [愿得一人]
    2021-02-01 05:22

    This thread is pretty old but I'll answer what I learned while searching on this topic for the future stumblers on this thread.

    The concept of privatizing a service with lazy loading is proper and for the below reasons:

    • When a module is lazily loaded it creates its own Injector context, which is the child of the root injector(it's parent injector to be precise). The services in them won't be pushed to the root injector as they were not instantiated when the root injector was being configured.
    • Angular Doc says that one of the ways to scope your service is to provide them to its own module(suppose Module-A). And only when any other module B imports module A, then it will have the provider of that service(from module A) and thus can access it. This actually works for lazy modules and not for eager modules for below reasons:

    • When you do implement the above scoping method for eager modules, it will create a provider for the services of that module(suppose module A). But when that particular module 'A' is imported into the root module(as all eager modules should be), the root injector will create a single instance of that service and would discard any duplicate instance of that service in the root injector's scope(if module A was imported in any other eager module). Thus all eager modules have access to a singleton service of any module which was imported in the root module.

    • Again at application load the root injector and module won't know about the lazy module and its services. Thus the lazy services are privatized in their own module. Now for the root module to have access to the lazy service, it needs to follow the angular way of importing the module. Which is basically importing the "supposed to be lazily loaded" module into the root module at application load time, and thus defeating the purpose of lazy loading.
    • If you still want to have access to the lazy service from the root injector. You can use the:

      @Injectable({ 
          providedIn: 'root'
      })
      

    decorator in the lazy service and inject it in the root injector without loading the lazy module at application load.

    The example you were following is not a true implementation of lazy loading if you have access to the lazy services in your root module, without the providedIn: root object. You can go through this link: https://angular.io/guide/providers#limiting-provider-scope-by-lazy-loading-modules

提交回复
热议问题