What are benefits of using store (ngrx) in angular 2

后端 未结 3 382
旧时难觅i
旧时难觅i 2020-12-12 16:07

I\'m working on a angular 1.x.x project and thinking about upgrading my code to angular 2.

Now in my project I have many services

3条回答
  •  长情又很酷
    2020-12-12 16:35

    ngrx.store does what a well designed component/service will do, with added benefits. So far, and I'm early in working through how this comes together, this is what I've found:

    It is really easy to get an unmaintainable mess with services and components. If you have cascading actions, complex data interactions and calls to remote locations you end up structuring a service that is almost identical to the action-reducer-store arrangement in ngrx. Small pure functions, observables, etc. ngrx has it already, why not use it and gain from the thought and patterns that it represents.

    If forces/encourages thinking in small testable functions. To lay out a reducer or multiple reducers for a moderately complex component enforces a discipline that will remove so many of the hour consuming pitfalls. Nothing swallows hours like tracking down a quasi multithreaded race condition stemming from the callback queue. I'm sure this can happen with reducers, but it simplifies access to the call sequence and state for debugging.

    The Angular2 pattern becomes easier. Templates with the display logic, components as a gathering place of all the bits and pieces that the template needs. Services become simpler as they simply do remote calls or handle the io for data from wherever it comes from. Then the actions and reducers for maintaining and changing the state, which triggers all the other parts to respond to the new state. I found that with component/service pattern either one would start getting big and complicated, with the side effect of it becoming extremely difficult to debug. My services were ending up storing the state and doing the data io.

    Observables. Everything is an observable in rxjs.store, and that is the basis for a responsive app. Structuring app state as an observable is sometimes a bit arcane or not very straightforward, but figuring it out and doing it well pays large dividends further down the line.

    The only negative that I can see is that the reducers become extraordinarily large very quickly. There seems to be lots of situations where the same code with different names is repeated, and repeated. My brain screams out 'function with parameters', but it doesn't work that way. On the other hand, this is where the structure and state of the app is expressed in all it's detail, so there is bound to be lots there. And when something goes wrong, as it inevitably will, having a pure function as the source of the problem makes it easier to track down and fix.

提交回复
热议问题