Real Time Example of NGRX + Angular

Nikhil Kapoor
4 min readAug 17, 2018

--

If you haven’t read my previous articles, Please do read them

  1. 3 W’s with NGRX
  2. It’s All About NGRX

or before reading my current article you should know what is Ngrx and some basic jargons of NGRX.

What we are going to cover ?

  1. Modules used in NGRX ( NPM Libraries )
  2. Integrating NGRX router with application
  3. Setting up the store for Employee and Getting Data ( Next Article )
  4. CRUD operation using NGRX ( Next Article )
  5. Unit Testing of NGRX ( Next Article )

I have created a basic angular project with NGRX on my Github. This project may help you for the clear understanding.

Why am I writing this article ?

Personally, I am not able to find any real-time example application of NGRX over the internet except increment and decrement. So in my article we will follow the real-time scenario. We will move slowly so please be patient.

Let’s start with How to use NGRX?

Modules used in NGRX ( NPM Libraries )

We need to install some of ngrx libraries which are as follow :

· @ngrx/effect

· @ngrx/entity

· @ngrx/router-store

· @ngrx/store

· @ngrx/store-devtools

· ngrx-store-freeze

@ngrx-store

  • @ngrx-store module is needed to activate the state management of your application. We are going to use many features of store module like actions,reducer etc
  • StoreModule.forRoot is imported once in the root module, accepting a reducer with the metaReducder

@ngrx/entity

  • @ngrx/entity lets you create entity adapters for different kinds of entities. Using an entity adapter, you can quickly write reducer operations and automatically generate selectors. How ? we will see in the example

@ngrx/router–store

  • The `RouterStateSnapshot` provided by the `Router` is a large complex structure.
  • A custom RouterStateSerializer is used to parse the `RouterStateSnapshot` provided
  • by `@ngrx/router-store` to include only the desired pieces of the snapshot.

@ngrx/effects

  • Ngrx/effects is middleware for handling side effects in ngrx/store. It listens for dispatched actions in an observable stream, performs side effects, and returns new actions either immediately or asynchronously.

@ngrx/store-devtools

  • We will be using the store dev tool to see the redux result or to debug the application

ngrx-store-freeze

  • we will be using this module as a meta reducer for ngrx/store to freeze our current state which is immutable and in case if any one try to abuse the state , an error will be thrown

We are done with theory part… Let’s move on to some magic now

Integrating NGRX router with application

In this section, We will give “NGRX super powers” to our application and then we will add ngrx router to check whether ngrx has been implemented or not

Step 1: Go to your appmodule.ts and add the following code

Line Number 2–6 we are importing the module, as discussed in previous topic.

Line Number 8 is creating a metaReducer using storeFreeze Module, But what will storeFreeze Module will do ? storeFreeze Module will only “FREEZE” your state so that you can’t mutate the state in development mode.

Line Number 16 is expecting 2 arguments one is general app reducer and the second argument is configuration, in our case it is metaReducers(store-freeze)

Line Number 18 will connect Angular’s routing with Store’s routing so it is behaving like a bridge in for routing in Angular and store.

StoreDevToolsModule will give you an overview of your redux and state management. For this you have to install a chrome extension reduxdev tool.

After the successful implementation of NGRX, you can go to your chrome extension and can see the beautiful diagrams and charts of redux application. like

ReduxDev Tool

Step 2: Create a new file and name it root.reducer.ts and add

import * as fromRouter from '@ngrx/router-store';export const appReducer = {   routerReducer: fromRouter.routerReducer,};

Since we were using this appReducer in our appModule.ts hence we will import this in our AppModule.ts and will pass appReducer in store.forRoot as a parameter.

we are done with providing the super powers to our angular application and it's time to activate/use them.

Now we will create NGRX for routing, So whenever there is some change in url or routing we can get a notification using NGRX

Update your App.module.ts

We added provider in this file

Update your Rootreducer.ts file as

Why we need this ?

According to ngrx team, The current object of angular router snapshot is very heavy… so in case with ngrx we are customizing our need like now i just want have url , query Params and params in my router snapshot so we will create a interface as

export interface RouterStateURL {   url: string;   queryParams: Params;   params: Params;}

Now we have to override the angular’s router so in that case we will implement RouterStateSerializer<RouterStateURL> as

export class CustomSerialier implements RouterStateSerializer<RouterStateURL> {
serialize(routerState: RouterStateSnapshot): RouterStateURL {
const { url } = routerState;const { queryParams } = routerState.root;let state: ActivatedRouteSnapshot = routerState.root; while (state.firstChild) { state = state.firstChild; } const { params } = state; return { url, queryParams, params }; }}

In the above class we are hijacking the function serialize and creating the wrapper on it as we want and in the end we will get an object of

{
url : ''
queryParams: ''
params: ''
}

and we are done… Now you can go to your Redux dev tools and see the magic

I’ll continue the next topic in my upcoming articles

I hope that you’ll like my articles… Please appraise me with your feedback :)

--

--