Search code examples
angularrxjsstorestate-managementbehaviorsubject

Service based management: should I seperate methods and states?


I use a state management based on BehaviorSubject in my angular app. I have a service that manage products. Should I separate states and methods in differents services like so :

products-states.service.ts:

  • products
  • get products
  • set products

products.service.ts (inject products-states.services):

  • add products
  • remove products

It sounds good to separate responsabilities but the more the app is growing, the more I need to inject services in other services.

If I have a cart.service.ts and card.states.service.ts that needs products services, it starts to be messy and difficult to test.

Should I split them? Did I miss something?


Solution

  • As long as you keep the services logical, by that I mean, cart service takes care of cart related logic, product service takes care of product related logic, there is a logical grouping of functionality which gives your project services a singular purpose.

    As for the states services that you use separately, you can just inherit them by using extends so that the logic is separated into two separate files, but the methods can be accessed through inheritance

    export class ProductService extends ProductsStates {
        constructor(...) {
            super();
        }
        ...
    

    We cannot avoid cross communication between services like productService and CartService since products need to be added to the cart. But dependency injection is already a logical grouping through services so we can import them and use them, wherever necessary.

    Your constructor might be a little crowded (as you mentioned), but DI is good for sharing code quickly and easily!