ngRx With Redux in Angular
ngRx With Redux in Angular
In this article, we discuss some basics behind getting started with ngRx with Redux in Angular to build more efficient SPAs.
Join the DZone community and get the full member experience.Join For Free
Redux is available as a package on NPM for use with a module bundler or in a Node application:
So, let's discuss the basic concepts of Redux.
So, now, we will see the overall concept of Redux and see hows it works. Here, we can see that we have a UI, and when a user performs an action, it will change the state of the data within the application.
What Is State?
Basically, all data within an application is collectively known as the store, and it is represented as a state. We cannot change the state, as it is immutable. We can change the state only using Action, which itself is an object made up of two components:
- Type: Type is nothing but an Action Name.
- Payload: Alternatively, Payload is something we can refer to as Action Data.
You may also like: Angular Tutorial: State Management With ngRx.
How it Works
When data changes, the existing state is duplicated. Then, a new object is created with the updates. In Angular, this data is treated as an RxJS Observable, allowing us to subscribe to it from anywhere in the app. When an event is emitted, for example, a button is clicked, the action is sent to a reducer function to convert the old state into the new state:
Here, you can see that in action, Delete_Item is our action name and 123 is an action data.
How to Configure ngRx
ngRx is an angular version of the redux pattern, which is inspired by the group of libraries inspired by the flux pattern.
You can set up ngRx with just two steps described below:
Create a new app with Angular-CLI and assign a name to it. (In our case, we're calling it, ngrProject.)
Install the ngrx/store via npm in your system with the following command.
Here, in this file, we need to update the app module file with the post reducer, for that we need to import the post reducer.
Now, we will create one another file in which we create the reducer.
Here, we have switch statements with the possible actions and this whole function is collectively known as a reducer. In this function, the switch statement returns the statement as 'i am learning' in different languages depending upon the actions.
So now if we want to change the state and we will use the class store then we need to implement interface corresponding to the object necessary to pass to the
A variable for message$ is set as an Observable on the component by calling
We trigger state changes by sending actions to the reducer with
Now, we can subscribe to the Observable in the HTML and trigger changes with button click events.
Conclusion: I hope this blog is useful for you to get a basic understanding of ngRx with redux. Happy coding!
Thanks for reading!!!
Opinions expressed by DZone contributors are their own.