Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Difference between service and redux

What is the need of redux because we can also save and get data from services, as far as I understand we can also get and save data into services and those services could be used by other components.

like image 895
blackHawk Avatar asked Aug 12 '16 05:08

blackHawk


1 Answers

You don't need redux, but you do need a way to maintain state. A service will do, but in the end you will send up with something resembling redux or ngrx store.

Consider the challenge. You have data coming in asynchronously. You want it reactive. You want to have error handling. You want to have waiting states as data is updated. You have cascading scenarios where one event triggers multiple actions, each with its own latency and error paths.

And you want to set up a pattern that can be used in multiple components.

Victor Savkin has a way of doing this with observables which is very slick. Ngrx has another way.

I wrote a moderately complex component using a service. It worked ok. Hours would disappear into tracking down some odd situations where the state was undefined and threw errors. I was getting far too much into the weeds to have something reusable as a pattern. And the result was fragile and brittle. It wasn't fully reactive, and to make it was proving extremely difficult and time consuming. I ported it to ngrx, and once the learning curve is surmounted, which isn't trivial, the code became simpler and fully instrumented allowing quick debugging.

YMMV.

Victor Savkin has an article on how to maintain state

like image 72
Derek Kite Avatar answered Oct 19 '22 01:10

Derek Kite