What is the recommended approach for initializing and releasing mutable services based on subdomains and routes in Angular?

  Kiến thức lập trình

We use Angular for our application. We have some kind of mutable (state) services that we call them Repository services. For example, PortfolioRepository, where we call an API to get all portfolio items also, to listen to socket messages to update our list.

the challenge is that we have a big application with different subdomains. Also, we have dozens of these services. When the user visits a non-related page I should stop listening to the socket in this service and empty the memory. when we return to a related page, everything must start again.

Also, we have the login page and other public pages where everything must stop.

one way is to provide these services in the needed page components but we need to have wrapper route components for all related domains because we do not want our service to be destroyed and created per each related domain page.
the other disadvantage is that every other service that imported these services should not be provided in root, because they will make their own (per root) services. so, we will have plenty of services that we should provide in wrapper components.

one other way is to start/stop services in subdomains. this method is also very bug-prone and needs very careful methods for starting (not initializing) and stopping (not destroying) and also, careful decisions for “where” to stop and start them.

It’s worth noting that based on my experience, modules are not good places to provide services because they only construct a service but do not destroy them when we leave the modules. also, using “providedIn: ModuleName” in the service also creates circular dependency problems.

What is the recommended approach to initiate and release these mutable services?

LEAVE A COMMENT