Implementing NgRx in Angular: A Comprehensive Guide

Hamid Hassani
Mobiroller Tech
Published in
8 min readApr 25, 2023

NgRx is a state management library for Angular applications that follows the Redux pattern. It provides a predictable and centralized way to manage the state of an application, making it easier to handle complex state management scenarios. In this article, we’ll explore how to implement NgRx in an Angular application step by step.

by the way, if you are not familiar with NGRX and state management you can read my previous article that described the basics concepts of NGRX, https://medium.com/mobiroller-tech/ngrx-in-angular-1a07d4ec2451, also it’s worth noting that if you like to watch a video about ngrx subject, I have uploaded ‘How to use NgRx in Angular — YouTube’ video on my youtube channel, follow the link and watch that out.

How to implement NGRX in action?

Step 1: Install NGRX Packages
The first step is to install the required NGRX packages in your Angular application. Open a terminal and navigate to your Angular project’s root directory. Then, run the following commands to install the required packages:

Installed packages usage:

· @ngrx/store, used for managing the store

· @ngrx/effects, used for handling side effects in store

· @ngrx/store-devtools provides developer tools and instrumentation for the store, with this package we can monitor the changes of the store in the browser

Step 2: Create the Store (state)

Let’s suppose we want to create a store for the user module so we tend to store user profile information in our store. In order to do that let’s create a folder in our user profile module called data-access, in data-access create a store folder. So far so good, we’re gonna define all the required stuff of the user profile store here. Start with creating a file called user-profile.reducer.ts (forget other files for now, I will explain what they are and what we should about them)

In this file, we need to define our store (every time that we create a store we need to feed/initialize it)

Step 2: Create your Actions

Before diving into this part let me explain the Action concept in Ngrx. In fact, Actions are nothing but an event(or command) that you dispatch/issue in your project in order to do a specific job like fetching user data from API, or updating an existing product, etc.

Examples:

· loadUserProfileInformation

· GetListOfApps

· LoadStoreInformation

· LoadWebSaleChannelData

Let’s continue with coding 😊, let’s imagine we want to fetch our user profile information from the server, so the first step would be defining a service class that calls http request for fetching the desired data, right? Therefore let’s create the user.service.ts, in this service class we will have something like the below:

Now it’s time to define our actions in terms of issuing a command to NGRX hey I want you to do something for me, since we are going to talk with NGRX about user profiles let’s create actions about that topic.

In addition to loadUserProfileInformation, there are two other commands here which are loadUserProfileInformationSuccess and loadUserProfileInformationFailure, don’t panic they are nothing but complementary commands of loadUserProfileInformation. It means if we want to issue the command we just need the simple loadUserProfileInformation action (I will tell you what is the usage of other commands a little bit later)

As the last point about Actions I would say, we will dispatch actions in the components with dispatch command like this:

It’s getting interesting I guess, let’s dive into reducers which is the next piece of the NGRX puzzle

Step 3: Create a Reducer

What is a reducer?

Is that your question? Okay let me explain it this as well, Reducer is a pure function that takes the current state (which is userProfileFeatureState) and an action as input and returns a new state. hold on, I thought it got complicated, let me put it this way, imagine you have a listener that listens to what components are demanding from the store. Remember our greeting component? It wanted to load user profile information.

So reducers tend to listen to these commands (actions that dispatch from components), and based on what is received it executes a method that changes the store somehow.

Now, it’s time to explain the actions in the reducer.

1. loadUserProfileInformation: this action is dispatched from the component, when it is received by the reducer it will start to call an API so it’s going to take time, in the meanwhile the only part that we must change in our state is the status, so we change it to loading

2. loadUserProfileInformationSuccess: this action will dispatch when we receive our data from API side.

3. loadUserProfileInformationFailure: this action will dispatch when we received an error from API side, like times we get 500 or 401 error.

Probably you got confused again, but wait for the last part of this puzzle, which is effects.

Step 4: Add Required Effects

What is the effect?

An effect is a class that listens to actions and performs movements consequently for those actions. Again it got confused you? All right, here is the thing, You probably want to perform API calls, database operations, or logging when an action is dispatched, how do you want to do that? Your solution would be using effects. Indeed, Effects are supposed to do extra operations when an action is dispatched through the application, Let me make it clear with our scenario which is loading user profile information. Let’s say you want to call getCurrentUserProfile API when loadUserProfileInformation action dispatch what you need is to define an effect and listen to an action like this:

As depicted in the image when loadUserProfileInformation dispatched, loadUserProfileInformation$ will trigger cause it’s filtering dispatched actions via OfType operatore which belong to ngrx/effects package, then when user information recived successfully from API side we are returning loadUserProfileInformationSuccess which will update the store, the error part is empty by you can simple return loadUserProfileInformationFailure action as result and update the store with error value.

We are done by the concepts of NGRX up here, just a simple one is remains which is selector.

Step 5: Read Store data via Selector

Up to now we were discussing about data manipulation in NGRX but it’s time to know how we can use/read this data, we can do this simply by selectors.

What is Selector in NGRX?

Selectors are pure functions used for obtaining slices of store state, before we grab a slice of store state we need to define a feature selector that tracks the state changes and provide it’s data for us. As depicted in the below image we defined userProfileState as our feature Selector the we are passing it to our selectors and grab portion of store state.

How to use Selector?

It’s as simple as calling the select method of the store, see the example, and you definitely find out how to use it.

Step 6: Configuring NGRX in our application

So far we understood the core concepts of NGRX, also how to manipulate data and select data from the store but all that we did so far would be nothing if we don’t configure the store into our project, it means we have to register the store into our project. Let’s do that, but before jumping into coding in this part I want to mention that there are various workarounds for registering the store into the app module, mind you for the sake of simplicity, maintainability, and having more clean code I would suggest my solution.

Normally in my projects I create a core module and define a folder in that module called store, in this store folder I hold everything related to ngrx which is global, like the list of reducers/effects. When I provided the required data and everything would be ready I register the store in the core module like the below.

Now let me explain the code line by line, let’s start with line 12:

In this line, I just register Reducers that are kept in the app.reducer.ts file

By the way, there is a strange thing for you in this image, and it’s FeatureKey, you might wonder what is that?
Frankly, as its name suggests it’s key when we register a feature, we tie to it the reducer using a string, so it would be something like the below

The next line is the place we are registering Effects, we are adding features effects in app.effects.ts file

Last but not least is related to store dev tools that help us to monitor store changes in a visual manner (Since it’s not our topic here I probably write a different article for that later on)

As the final step don’t remember to register core.module.ts into app.module.ts.

Conclusion

NgRx is a powerful state management library for Angular applications that provides a centralized way to manage the state of an application. In this article, we explored how to use it for specific features of our project and what are the core concepts of that. Definitely, there are tons of concepts and tricks that I couldn’t cover in this article thereby I would suggest being more curious about NGRX at the end I hope you like this article. cheers.

--

--