Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ngxs - Call an Angular service : good practices?

When I use ngxs what should my app do:

  • my component calls a service and the service dispatches an action with the result as the payload?
  • my component dispatches an action and my State calls the service?
like image 762
Vincent Nabet Avatar asked Oct 19 '18 13:10

Vincent Nabet


3 Answers

My opinion is that the Dispatched Action should itself be immutable and not to be used to return result. Instead, client interested to know result (usually in state change cause by an Action) should subscribe to the state change. Note that NGXS is a CQRS implementation.

like image 147
KY Chin Avatar answered Oct 19 '22 19:10

KY Chin


You can do both and if you look into open source apps you'll probably find both.

So far I've personally (with ngrx but it's the same) injected the store and dispatched actions from the (smart) components.

But I've been reading a lot of articles about facades lately and I think it's actually the right way to go in order to keep your components as simple as possible but especially to simplify the testing too.

You can read more about facades here:
https://medium.com/@thomasburleson_11450/ngrx-facades-better-state-management-82a04b9a1e39

https://medium.com/default-to-open/understanding-a-large-scale-angular-app-with-ngrx-80f9fc5660cc

https://blog.nrwl.io/nrwl-nx-6-2-angular-6-1-and-better-state-management-e139da2cd074

like image 31
maxime1992 Avatar answered Oct 19 '22 19:10

maxime1992


As stated, you can do either - here's an earlier question I posted with a response from one of the NGXS team.

In our project we've followed this pattern, dispatch an action, have the state's action handler call the service, then patch the state with the result. And if needed, dispatch further actions to indicate success or failure.

like image 2
Garth Mason Avatar answered Oct 19 '22 18:10

Garth Mason