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
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:
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.
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