How to Use State Inside of an Effect Component With ngrx
Join the DZone community and get the full member experience.Join For Free
For this post, I assume you already have knowledge about ngrx (a reactive state management framework for Angular), and you are working with reducers, actions, effects, and selector components. You can find information in ngrx. Today, I want to show you how to work with state inside of the effect component.
This is a very simple example of an effect. It's defined by the
getInfoAction action, and there is a call to service
getInfo. Then, it's fired the action,
getInfoSuccessfulAction. At this point, everything is straightforward, but what if you need to get some value from @ngrx/store. Well, the good news is you can do it; let me show you how to.
The idea is to inject a
Storage instance into the Effect. Then, you can use it in your effect factory method.
Then, you constructor looks like this:
Now, you can use your
storage object to get data from your current state. (You can use a Selector.) I am going to show you my create effect method updated to use the
withLatestFrom: The method to use your selector.
getInfoName: The regular ngrx selector.
infoName: The value return by the selector (you can use it as a parameter on your call service).
In this way, you can use a value saved into your storage inside your effect. Now, I want to show you an example with more complexity. How you can use this approach when the action used by your effect has parameters. Do not worry about the solution. It's really easy.
This is the action definition with a parameter (A string parameter the parameter's name is greeting).
This is the effect definition using the
greetingAction and a value (current user name) from
Opinions expressed by DZone contributors are their own.