ngRx with Redux in Angular

Reading Time: 4 minutes
REdux


In this blog, we will see the basic pattern of Redux and some benefits and some high-level concepts of redux and then we will discuss the brief about ngRx and its basic implementation.

Redux: Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time-traveling debugger.

Redux is available as a package on NPM for use with a module bundler or in a Node application:

npm install --save redux

So let’s discuss the basic concepts of redux which are also used for Redux.

ngrx-redux-pattern-diagram


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.

Here the question arrives, What is the state?

Basically, all the application data is collectively known as the store and it is to be represented as a state.  Also, we cannot change the state as it is immutable. We can change the state only using Action, which itself is an object which included two things:


1: Type:
Type is nothing but it is an Action Name.


2: Payload:
Alternatively, Payload is something we can refer to as Action Data.

Example of  Action:

{ type: ‘DELETE_ITEM’, payload: 123 }

Here, you can see that in action, Delete_Item is our action name and 123 is an action data.

So How’s it works?

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

2: When an event is emitted, for example, a button click, the action is sent to a reducer function to converts the old state into the new state.

NgRx: The ngRx is an angular version of the redux pattern. Which is inspired by the group of libraries inspired by flux pattern. what do I mean with “angular/rxjs” version of redux The angular part is because ngrx is a library to use within an angular application. The rxjs “part is because of the implementation of ngrx works around an rxjs flow.

ngrx

 

How to configure ngRx?

You can set up ngRx with just 2 steps described below:

1: create one new app with Angular-CLI and give it any name to it.

ng new ngrxProject --routing
cd ngrxProject

2: Install the ngrx/store via npm in your system with the following command.

sudo npm install @ngrx/core @ngrx/store --save

Now let us understand this concept with the help of the basic example shown below:

app.module.ts

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.

import { StoreModule } from '@ngrx/store';
import { simpleReducer } from './simple.reducer';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    StoreModule.forRoot({ message: simpleReducer })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

ngrx.reducer.ts

Now, we will create one another file in which we create the reducer.

import { Action } from '@ngrx/store';

export function simpleReducer(statement: string = 'I am learning',
 action: Action) {

  switch (action.type) {

		case 'German':
		  return statement = 'Ich lerne'

               case 'FRENCH':
                 return statement = 'j'apprends'

		default:
		return statement;      
	}
}

So, 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.

app.component.ts

  • 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 ngModule.

  • A variable for message$  is set as an Observable on the component by calling this.store.select(‘message’).
  • We trigger state changes by sending actions to the reducer with this.store.dispatch (‘ACTION’).
    import { Component } from '@angular/core';
    
    import { Store } from '@ngrx/store';
    import { Observable } from 'rxjs/Observable';
    
    interface AppState {
      message: string;
    }
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
    
      message$: Observable<string>
    
      constructor(private store: Store) {
        this.message$ = this.store.select('message')
      }
    
      germanMessage() {
        this.store.dispatch({type: 'GERMAN'})
      }
    
      frenchMessage() {
        this.store.dispatch({type: 'FRENCH'})
      }
    }

Now we can subscribe to the Observable in the HTML and trigger changes with button click events.

<h2>{{ message$ | async }}</h2>

<button (click)="GermanMessage()">German</button>
<button (click)="frenchMessage()">French</button>

Conclusion: I hope this blog is useful for you to get the basic understanding of ngrx with redux after reading this blog and you will start using it in your application.

Thanks for reading!!!

Written by 

Nitin Arora is Software Consultant at Knoldus Software LLP with 6 months of experience. He has done MCA from Banarsidas Chandiwala Institute of Information technology, Delhi(GGSIPU). He has a graduation degree in BCA from Jamia Hamdard. He has a sound knowledge of various programming languages like C, C++, Java, and scala. Also has a deep interest in frontend development like Html, CSS, Angular, Javascript. He is currently working in frontend technologies like Angular, Html, CSS, Bootstrap and Typescript. He is focused, hardworking, team-oriented member and always exploring new Technologies, His hobbies is to play cricket, volleyball, and do coding.

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!