SharedModule
and instead of defining our service in the providers
property, we need to create a static method called forRoot
that exports the service along with the module itself.AppModule
calling the forRoot
method to register the module and the service.forRoot
in the root application module and no where else. This ensures that only a single instance of your service exists at the root level. Calling forRoot
in another module can register the service again in a different level of the DI tree.SharedModule
only consists of a service that Angular registers in the root app injector, we do not need to import it in LazyModule
. This is because the lazy loaded module will already have access to services defined at the root level.counter
property, this value is shared between the EagerComponent
and the LazyComponent
proving that we are using the same instance of the CounterService
.SharedModule
that we'll need in another module. Take the following for example.HighlightDirective
so other modules that import SharedModule
can use it in their templates. This means we can just import the module in LazyModule
normally.LazyModule
without creating another instance of CounterService
.