angularangular-servicesangular-lazyloading

how to share same service instance between 2 lazy loaded modules - not at root


Is it possible to share the same instance for a service, between two lazy loaded modules, where that service is not provided at the root injector? Or at least, not provided until called upon?

E.g. I have LazyModuleA and LazyModuleB that are, as named, loaded lazily. Each of these modules need access to the same service, but that service is not needed anywhere else. The shared service should only have a single instance shared among the modules. Also, it should not be loaded or accessible outside those two modules.

Currently I'm providing the service in the root injector via {providedIn: 'root'} . Is it possible to load the same instance of this service for both of these lazy loaded modules?


Solution

  • Interesting, I am not sure if this would work, I haven't tried myself, how about if you have a 3rd module, in it, there is your service without providerIn: root.

    Your service:

    @Injectable()
    export class MySharedService {
     // ... some code
    }
    

    This 3rd module:

    @NgModule({
       providers: [MySharedService],
       exports: [MySharedService] // I'm not sure if this is need it 
    })
    export class ModuleC {}
    

    LazyModuleA:

    @NgModule({
       import: [ModuleC]
    })
    export class LazyModuleA {}
    

    LazyModuleB:

    @NgModule({
       import: [ModuleC]
    })
    export class LazyModuleB {}
    

    So your LazyModuleA and LazyModuleB both have imported ModuleC which is exporting your desired service.