Redux is a reactive state management library which is developed by Facebook and used in the React library. It is based on the Flux pattern. The difference between Flux and Redux is how they handle tasks; In the case of Flux, we have multiple stores and one dispatcher, whereas, in Redux, there is only one Store, which means there is no need for a dispatcher. Redux is a person who is incharge of managing data flow in your application.
We need to use the NgRx library to use Redux in the Angular framework. NgRx is a powerful library for organizing and managing state and interactions with the state in your Angular applications following the Redux pattern. It is a reactive state management library. With NGRX, we can get all the events (data) from the Angular app and keep them all in one place.
We are going to cover the concepts below in this blog post.
- What is NgRx?
- Why use NgRx?
- Redux Pattern
- Sample application
What is NgRx?
NgRx is a framework for building reactive applications in Angular. NgRx provides libraries for:
- Managing global and local state.
- Isolation of side effects to promote a cleaner component architecture.
- Entity collection management.
- Integration with the Angular Router.
- Developer tooling that enhances developer experience when building many different types of applications.
Libraries that comprise NgRx are as follows:
- @ngrx/store
- @ngrx/store-devtools
- @ngrx/effects
- @ngrx/route-store
- @ngrx/entity
- @ngrx/schematics
- @ngrx/component-store
Why use NgRx?
Without NgRx we need a service for each bit of state with complex applications it will become very complex for the developer. With NgRx we doesn’t require a service for each bit of state, rather we have a single store for our application state making it easy to find, track and retrieve state values.
- Avoids multiple http calls with state cache
- Helps in complex component interactions
- NgRx allows us to use tools to view list of actions and our state.
- Rollback and time travel debugging.
Without NgRx
A simple product list example without NgRx.
We may have a data access service that looks like this. We get our product from back end server using Http.
Our component calls that service
Notice that this code is on the ngOnInit() method. That means when the user navigates to this page the component calls the service to issue a http get request that retrieves products from the server.
if the user navigates away even if for a movement and navigates back the component calls the service to get the data again. If the data changes frequently that may be desire but some data just doesn’t change that much so there were no need to get it again.
So here comes the use of NgRx. With NgRx the store provides the client side cache so we don’t need to get data from the server every time the component is initialized.
Redux Pattern
Redux is a predictable state container for javascript applications.
Redux Principals
- Single source of truth called the Store
- State is read only and only changed by dispatching actions
- Changes are made using pure functions called reducers
Store is RxJS powered global state management for Angular applications, inspired by Redux. Store is a controlled state container designed to help write performant, consistent applications on top of Angular.NgRx Store provides state management for creating maintainable, explicit applications through the use of single state and actions in order to express state changes.
Actions describe unique events that are dispatched from components and services.
- type: It is a read-only string that describes what the action stands for. For example, Login.
- Payload: This property type depends on what type of data action needs to send to the reducer. In the previous example, the payload will be a user object. Not all actions need to have a payload.
Examples
- Login action after login form submission
- Toggle side menu option after a button click
- Retrieve data action when initializing a component
- Start a global spinner action while saving data
Reducers are functions that specify how state changes in response to an action.
Reducers are responsible for handling transitions from one state to the next state in your applications.Reducers are functions and handle each state transition synchronously.
Examples
- Set a userDetails property on login
- Toggle a side menu visible property to true on button click
- Set successfully retrieved data on component initialization
- Set a global spinner visible property to true while saving data
Advantages of Redux Pattern
- Centralized immutable state
- Better view performance
- Testability
- Tooling
- Component communication
Sample Application
This article will show how easy it is to create a simple application using Redux and the NgRx libraries. But before starting the development, we have to make sure that we have installed angular-cli on our computer.
1. The first step is to generate a new Angular CLI application using the below command in the terminal:
ng new angular-state-management –style=scss –routing=false
It will create all the required files and install the dependencies. This will take a few minutes. Open the project in VS code.
2. Let’s run the app created by the CLI, just to make sure everything has been created correctly so far with below command:
npm start
Check that the app is running on http://localhost:4200/.
3. Install NgRx and Tools
NgRx Schematics provides scaffolding. NgRx commands get integrated into the Angular CLI, and most of the NgRx elements can be created using angular CLI. So, let’s add NgRx Schematics. (You can use a new terminal window or exit out from the running angular app by pressing the Ctrl+C key )
ng add @ngrx/schematics@latest
Configure the Schematics so that NgRx commands are available in Angular CLI by default.
ng config cli.defaultCollection @ngrx/schematics
Let’s install the NgRx, dependencies, and dev-tools now.
npm install @ngrx/store –save
npm install @ngrx/effects –save
npm install @ngrx/entity –save
npm install @ngrx/store-devtools –save
Notice that package.json has been updated.
4. Add an NgRx Store to the App
Let’s generate a NgRx Store in the app.
ng generate @ngrx/schematics:store State –root –module app.module.ts
Notice that the following line has been added to the app.module.ts
StoreModule.forRoot(reducers, { metaReducers }),
5. Create a sub Module for Customer
Let’s create a separate module for Customers following the ‘separation of concerns’ principle.
ng generate module Customer
6. Create a Customer model
Now, we are starting to add some code. First, let’s create a ‘Customer’ using the CLI.
ng generate class models/customer
As another option, you can add it using the editor.
The customer.ts file has been created in the src\app\models folder. Add ‘name’ property to it.
7. Add Actions
Now, we are going to add NgRx-related code. As our diagram above shows, the state that we are going to manage is the collection of customers. We can change the collection of the customer’s state using the actions. For this particular case, we have one action that can change the state:
We are not generating a failure action, So just select ‘N’.
ng generate action customer/store/action/Customer
? Should we generate success and failure actions? No
? Do you want to use the create function? Yes
CREATE src/app/ngrx/customer.actions.spec.ts (218 bytes)
CREATE src/app/ngrx/customer.actions.ts (132 bytes)
Create a TypeScript file, customer.actions.ts, in the src/app folder for customer actions using the editor.
Add the following code to the customer.actions.ts file:
8. Add a Customer Reducer
Let’s add the reducer; all state changes are happening inside the reducer based on the selected ‘Action.’ If the state is changing, then the reducer will create a new customer rather than mutating the existing customer list. In the case of the state change, the reducer is always going to return a newly created customer list object.
Generate reducer for Customers. Again, say “No” to adding failure, success actions.
ng generate reducer customer/store/reducer/Customer
? Should we add success and failure actions to the reducer? No
? Do you want to use the create function? Yes
CREATE src/app/ngrx/customer.reducer.spec.ts (334 bytes)
CREATE src/app/ngrx/customer.reducer.ts (237 bytes)
Add code to the reducer.
9. Add Selector
Generate a selector to get the customers from the Store.
ng generate selector customer/store/selector/Customer
Modify the code as below:
10. Add a UI Component for View Customers
Generate CustomerView component
ng generate component customer/CustomerView
Add code to the customers-view.compoment.ts file.
Declare the customers that are observable at the top of the class and modify the constructor and use the selector to get Observable of Customers
With required dependencies at the top, the customers-view.compoment.ts file should look like this now:
Add the following code to the customers-view.compoment.html file.
11. Add UI Controls to Add New Customers
Generate UI control component to Add Customers
ng generate component customer/CustomerAdd
Add code to dispatch the add customer action
With all modification the customer-add.component.ts
And the customer-add.component.html file.
12. Add StoreModule for Feature in Customer Module
Add Store module in the CustomerModule
Also, add the exports
The customer.module.ts will look like this:
13. Import the CustomerModule in the AppModule
Import the CustomerModule into the AppModule
14. Update the App Component With CustomerView and CustomerAdd Component
Now update the app.component.html file by removing the default content and embedding both the ‘app-customers-view’ and ‘app-customer-add’ components.
The app.component.html file should look like this:
15. Run the App
Comment (1)
Comments are closed.
nagalakshmi M R
February 11, 2022Please make a note that i blog where ever –save or -stle or -route is there you need to update with —