0
votes

There are situations where the cleanest solution to a use-case seems to be a combination of NGRX and a service. Is this wise, or does it violate the 'single source of truth' principle of NGRX?

For example, if I am using NGRX to build a shopping app I might have a store which includes:

  • An array of all products (objects) with name, product ID, cost etc.
  • An array of product IDs (strings or numbers) for the subset of products currently in the shopping cart.

The cart component would likely use a selector which filters all products by product IDs in the cart, but what about other components that need to know when an item is removed?

An array of 'removed' items is not going to be stored in the state, so one approach is to listen for a 'REMOVE_ITEM' action, and then update a service with the product IDs of the removed items. Components can then subscribe to this service and take appropriate action.

Is this good practise? If not, what is the recommended approach?

2

2 Answers

1
votes

NGRX propose some single 'source of truth' principe, but you are free to make changes if it's the cleanest solution for your app.

About your solution of storing data in services. It will works fine when you are using constant data.

But when multiples components will have to update this data you will probably encounter change detection and improper update issues, that you could solve with NGRX Store.

You can also check this : https://blog.angular-university.io/angular-2-redux-ngrx-rxjs/

0
votes

I believe the solution which most respects the 'single source of truth' principles of NGRX is to use the pairwise operator to subscribe to the most recent (n) and second most recent (n-1) iterations of the state:

this.activeFilters$.pipe(pairwise()).subscribe(state => {
  const currentState = state[0];
  const previousState = state[1];
  // Compare currentState with previousState to identify changes e.g.
  const removedItems = state[1].cart.filter(productID => state[0].cart.indexOf(productID) === -1);
});

currentState and previousState can then be compared for differences, which will indicate the most recent change.