When to use ngrx/effect in angular2

扶醉桌前 提交于 2019-12-03 02:51:11

If your case stays that simple, then you won't need an effect for it. Besides, the effect itself will do not much more than calling your service-method.

In short: If you project is very small and without many features, it will just cause you to write more code.

If you project is large, it will help you structure your data-flows and project-components.


When to use an effect:

When you want to trigger an action based on another action(in spoken english you would call this a side-effect) or when you want to add a generic error-handling or maybe a logging.

The way an effect works: The effect listens for any defined action(s) (e.g. LoadDataAction), then does some processing and returns any action(s) that are then processed by the store and distributed to a reducer or some other effect.

Example:

  1. LoadDataAction is dispatched
  2. an effect(loadData$) is triggered
  3. the loadData$-effect calls the data-service
  4. loading the data fails
  5. the loadData$-effect return a LoadDataFailureAction

ngrx processes the action...

  1. the LoadDataFailureAction might be picked up by:
    • a logger-effect(e.g. sends message to a server)
    • by an ui-notification-effect(e.g. displays message to user)
    • and/or by a reducer(e.g. persists the error-count or deletes something from the state)

To my understanding, you should to use ngrx/effects anytime you want to perform some asynchronous operation.

In a post on the subject, Jim Lynch says

"You can almost think of your Effects as special kinds of reducer functions that are meant to be a place for you to put your async calls in such a way that the returned data can then be easily inserted into the store’s internal state for the application."

link to article: https://medium.com/@flashMasterJim/the-basics-of-ngrx-effects-effect-and-async-middleware-for-ngrx-store-in-angular-2-f25587493329

I honestly believe that the majority of apps that are using ngrx shouldn't be. Stores solve problems that most forms based applications don't encounter.

Have a look at a library I am working on that gives the push based data flow benefits of a store but makes it incredible simple to setup and reason about without any of the ridiculous amount of boilerplate involved with ngrx.

https://github.com/adriandavidbrand/ngx-rxcache

It is based on RxJs Behaviour Subjects and gives you all the benefits of push based data flow and still allows you to use the dumb-smart component architecture.

I have redone the official ngrx demo application in it here

https://stackblitz.com/edit/github-tsrf1f

If you compare it to the official ngrx demo app at

https://stackblitz.com/github/ngrx/platform/tree/61cbfe537f9df8cef3dd4a6ee0b8f483e49653f4

You will see how much simpler it is to setup and work with.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!