Do we need state management in every Angular application? Maybe not always, so how do we implement state management elegantly for the applications in which we do need it? NgRx is one of the libraries used for application state management. It is a Redux implementation for Angular.

First, let’s look at the problem we are trying to solve, and then understand the concepts behind the NgRx, and, finally, we’ll jump into the coding.

Application State

What is the application state? Theoretically, it is the entire memory of the application, but, typically, it is the data received via API calls, user inputs, presentation UI State, app preferences, etc. Simply put, it is the data that can differentiate two instances of the same application. A simple concrete example of an application state would be a list of customers maintained in an application.

The Problem We’re Trying to Solve

For simplicity, let’s assume we have a list of customers in the application, and that is the state that we are trying to manage. Some API calls and user inputs could change the state ( i.e. the list ) by adding or removing customers. The state change should be reflected in the UI and other dependent components. Surely, in this particular case, we can have a global variable to hold the list and then add/remove customers from/to it and then write the code to update the UI and dependencies. But, there are many pitfalls in that design that are not the focus of this article. The NgRx is a great design for most of state management requirements. Indeed, it has a bit of boilerplate in comparison with other competitors like NGXS, Akita, or plain RxJS.

NgRx App State Management

Let’s look at the NgRx implementation — there are several components to understand. 

  • Store: The store is what holds the app’s state. 

  • Action: A unique event dispatched from components and services that describe how the state should be changed. For example, ‘Add Customer’ can be an action that will change the state (i.e. add a new customer to the list).

  • Reducer: All the state changes happen inside the reducer; it responds to the action and, based on that action, it will create a new immutable state and return it to the store.

  • Selector: Selector is a function used for obtaining a part of the state from the store.

  • Effect: A mechanism that listens for dispatched actions in an observable stream, processes the server response, and returns new actions either immediately or asynchronously to the reducer to change the state. Please note that we are not using ‘effect’ in this example app.

This is the interaction between those components in NgRx.

The user interface and other components dispatch actions. Actions can have a payload that needs to change the state. The reducer creates a new state as described by the specified action and returns it to the store. Once the store updates with the new state, it will notify the UI and all dependent components. Each UI reacts to the state change and its view gets updated to reflect the changes. 

This is the representation of our example state, the customer list.

The “Add New Customer” UI control dispatches the AddCustomer action with the new customer as a payload in that action. The reducer takes the AddCustomer action and the new customer comes as a payload and creates a new immutable collection with the existing customers. Then, it will update the store with the new customer list. Finally, it will notify the UI using the Observables and the UI gets updated with the new customers’ list.

Finally, the Coding

The code for this app is available here.

Prerequisites:

Make sure Node.js and Angular CLI are installed. Information can be found below links

To find out the Node.js and Angular CLI versions in your machine, run

node --version

ng --version

1. Create an Angular App With Angular CLI

Let’s create a new Angular Application 

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.

2. Load the Project Into the IDE (I’m Using IntelliJ IDEA)

3. Run the App

Let’s run the app created by the CLI, just to make sure everything has been created correctly so far.

cd angular-state-management 

npm start

Check that the app is running on http://localhost:4200/.

4. 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.

5. Add an NgRx Store to the App

Let’s generate 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 }),

6. Create a sub Module for Customer

Let’s create a separate module for Customers following the ‘separation of concerns’ principle.

 ng generate module Customer

7. 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 srcappmodels folder. Add ‘name’ property to it.

8. 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 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:

9. 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.

10. Add Selector

Generate a selector to get the customers from the Store.

ng generate selector customer/store/selector/Customer

Modify the code as below:

11. 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

customers$: Observable<Customer[]> 
constructor(private store: Store<CustomerState>) { 
 this.customers$ = this.store.pipe(select(selectCustomers));
} 

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.

12. 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 

  this.store.dispatch(addCustomer(customer));

With all modification the customer-add.component.ts

And the customer-add.component.html file.

13. Add StoreModule for Feature in Customer Module

Add Store module in the CustomerModule

StoreModule.forFeature(customerFeatureKey, reducer),

Also, add the exports 

exports: [CustomerViewComponent,CustomerAddComponent]

The customer.module.ts will look like this:

 

13. Import the CustomerModule in the AppModule

 Import the CustomerModule into the AppModule

11. 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:

12. Run the App

Our coding is done! Let’s run the app again (if it is not already running).

npm start

The app will look like this:

The code for this app is available here.

Thank you, your feedback on this article is highly appreciated.



Source link

Write A Comment