{{announcement.body}}
{{announcement.title}}

ngRx With Redux in Angular

DZone 's Guide to

ngRx With Redux in Angular

In this article, we discuss some basics behind getting started with ngRx with Redux in Angular to build more efficient SPAs.

· Web Dev Zone ·
Free Resource

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

Shell




x


1
npm install --save redux



So, let's discuss the basic concepts of Redux.

Redux workflow
Redux workflow

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 within the application.

What Is State?

Basically, all data within an application is collectively known as the store, and it is represented as a state.  We cannot change the state, as it is immutable. We can change the state only using Action, which itself is an object made up of two components:

  • Type: Type is nothing but an Action Name.
  • Payload: Alternatively, Payload is something we can refer to as Action Data.
You may also like: Angular Tutorial: State Management With ngRx.

How it Works

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. When an event is emitted, for example, a button is clicked, the action is sent to a reducer function to convert the old state into the new state:

JavaScript




xxxxxxxxxx
1


1
{ type: 'DELETE_ITEM', payload: 123 }



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

How to Configure ngRx

ngRx is an angular version of the redux pattern, which is inspired by the group of libraries inspired by the flux pattern.

Redux and RxJS = ngRX

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

Create a new app with Angular-CLI and assign a name to it. (In our case, we're calling it, ngrProject.)

Shell




xxxxxxxxxx
1


 
1
ng new ngrxProject --routing
2
cd ngrxProject



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

app.module.ts

Shell




xxxxxxxxxx
1


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



ngrx.reducer.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.

JavaScript




x
17


 
1
import { Action } from '@ngrx/store';
2
 
          
3
export function simpleReducer(statement: string = 'I am learning',
4
 action: Action) {
5
 
          
6
  switch (action.type) {
7
 
          
8
        case 'German':
9
          return statement = 'Ich lerne'
10
 
          
11
               case 'FRENCH':
12
                 return statement = 'j'apprends'
13
 
          
14
        default:
15
        return statement;      
16
    }
17
}



app.component.ts

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

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.

  • 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’).
  • JavaScript




    xxxxxxxxxx
    1
    30


     
    1
    import { Component } from '@angular/core';
    2
     
               
    3
    import { Store } from '@ngrx/store';
    4
    import { Observable } from 'rxjs/Observable';
    5
     
               
    6
    interface AppState {
    7
      message: string;
    8
    }
    9
     
               
    10
    @Component({
    11
      selector: 'app-root',
    12
      templateUrl: './app.component.html',
    13
      styleUrls: ['./app.component.scss']
    14
    })
    15
    export class AppComponent {
    16
     
               
    17
      message$: Observable<string>
    18
     
               
    19
      constructor(private store: Store) {
    20
        this.message$ = this.store.select('message')
    21
      }
    22
     
               
    23
      germanMessage() {
    24
        this.store.dispatch({type: 'GERMAN'})
    25
      }
    26
     
               
    27
      frenchMessage() {
    28
        this.store.dispatch({type: 'FRENCH'})
    29
      }
    30
    }


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

HTML




xxxxxxxxxx
1


 
1
<h2>{{ message$ | async }}</h2>
2
 
          
3
<button (click)="GermanMessage()">German</button>
4
<button (click)="frenchMessage()">French</button>



Conclusion: I hope this blog is useful for you to get a basic understanding of ngRx with redux. Happy coding!

Thanks for reading!!!


Further Reading

Topics:
ngrx ,redux

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}