Search code examples
angularangular-servicesangular-providersangular-injector

Share service instance between multiple components


Suppose you have 3 lazily loaded components, A, B, and C – this means they are not loaded eagerly, as soon as possible, but depending on some condition (e.g., a back-end response).

Is it possible to have them share the same instance of a service as long as any of them exist (i.e. are not destroyed)? After they've all been destroyed, and as soon as any one of them loads again, I'd like a new service instance to be created and shared among all the lazily loaded components, i.e. the whole process repeats.

I was thinking this could be done by restricting the service to a module. However, it appears modules, once loaded, are never unloaded, so the service instance continues to exist even after its declared components (A, B, and C) have been destroyed.


The approach outlined in https://stackoverflow.com/a/61163053/9445073 circumvents the problem by creating a Master component that provides the service instance to its Slave components. This setup doesn't suit my needs for flexibility because my components A, B, and C could be located anywhere on the page.

Solution

  • What you describe is against angular's lifecycles and I highly want to discourage you to try to change that.

    I think you should think more about some "session" instance and a service, that handles those sessions. The components register themselfes on this service. If there is no sessionContext active and a registration happens, the service creates a new sessionContext. If a deregistration from a component happens and it was the last service registered, clear the session context.

    The SessionContextService is provided in root and always available.