<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yatin Jain on Medium]]></title>
        <description><![CDATA[Stories by Yatin Jain on Medium]]></description>
        <link>https://medium.com/@yatinjain52?source=rss-9a2567e420ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UnbLOpALIOtHANhr</url>
            <title>Stories by Yatin Jain on Medium</title>
            <link>https://medium.com/@yatinjain52?source=rss-9a2567e420ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:57:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yatinjain52/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build Reactive Applications in Angular using NgRx]]></title>
            <link>https://medium.com/@yatinjain52/build-reactive-applications-in-angular-using-ngrx-4549d741c400?source=rss-9a2567e420ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/4549d741c400</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Yatin Jain]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 08:24:59 GMT</pubDate>
            <atom:updated>2020-05-07T10:36:00.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*2AgAGcAId-lpVzzXMihjqw.png" /></figure><h3><strong>What is NgRx?</strong></h3><blockquote>NgRx is a framework for building reactive applications using Angular, which provides state management, isolation of side effects, router bindings etc. that enhance developers experience during the development of different types of applications in it.</blockquote><h3><strong>What is Reactive Programming?</strong></h3><blockquote>Reactive programming is a term that you hear a lot these days, but what does it really mean?</blockquote><blockquote>Reactive programming is a way to handle events and data flow in your application. In reactive programming, you design your components and other pieces of your software in order to react to those changes instead of asking for changes.</blockquote><blockquote>Instead of pushing data directly to the component or service, in reactive programming, it is the component or service that reacts to data changes.</blockquote><h3><strong>Life-cycle of NgRx</strong></h3><figure><img alt="NgRx Life-cycle Flow Diagram" src="https://cdn-images-1.medium.com/max/1024/1*ZLCN3MZnahYuOy0zbkUWBQ.png" /><figcaption>NgRx Life-cycle Flow Diagram</figcaption></figure><blockquote><strong><em>1. Store:</em></strong><em> </em>Store has responsibility of holding the state and applying changes to it when they are told to do so (when an action is dispatched). State is handled only in one object and in one place, so debugging or adding changes becomes way easier.</blockquote><blockquote>You are never going to change the state directly instead you are going to dispatch actions. These actions describe what’s happening (can be things like getting, adding, removing, updating the state).</blockquote><blockquote><strong><em>2. Actions:</em></strong> Actions are objects that extend the NgRx Action class with a ‘type’ property. They have an optional ‘payload’ property (naming is up to you but the standard is to name it ‘payload’) for sending in data to the effect/reducer and are dispatched by the store to either run an effect or change state in a reducer.</blockquote><blockquote><strong><em>3. Reducers: </em></strong>Reducers are pure functions which produce the same output for a given input. It takes the latest ‘Action’ dispatched, the current state, and determines whether to return a newly modified state or the original state.</blockquote><h3><strong>Let’s Create An Example!</strong></h3><blockquote>Here I will create a basic CRUD example, using Visual Studio Code, which is recommended editor to build client side applications with its powerful features.</blockquote><blockquote><em>1. Install </em>Node Package Modules<em>, by running below command in package console manager.</em></blockquote><pre>npm install --save</pre><blockquote><em>2. Install </em>NgRx store.</blockquote><pre>npm install @ngrx/store --save</pre><blockquote><em>3. Add new folder </em><strong><em>e</em>mployee<em> </em></strong><em>in </em><strong>src/app </strong><em>folder (like below) in your application.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6aWdApSicPzGOLOsdt6A1Q.png" /></figure><blockquote><em>4. Add new files (as shown below) in </em><strong>src/app/<em>employee</em></strong><em>’s folder.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*nQIbgL0TITv-Ev89PnifIQ.png" /></figure><blockquote><em>5. Add new file </em><strong>app.reducer.ts </strong><em>in </em><strong><em>src/</em>app </strong><em>folder.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*jMqlc9Eiq06xvboc_0_6-Q.png" /></figure><blockquote><em>6. Add below lines of code into </em><strong>app/employee/employee.model.ts </strong><em>file. This is employee data structure which defines what type of data/properties we needed in this application.</em></blockquote><pre>export class Employee {</pre><pre>constructor(public <em>id</em>: string, public <em>name</em>: string, public <em>profile</em>: string) {}</pre><pre>}</pre><blockquote><em>7. Add below lines of code into </em><strong>app/employee/employee.action.ts </strong><em>file.</em></blockquote><blockquote>Here each action has its own unique identifier. ‘<strong>type</strong>’ property for each action is mandatory to define, so that store will able to identify what type of action it needs to dispatch.</blockquote><blockquote>On the other hand, ‘<strong>payload</strong>’ property defines the data which needs to be pass at the time of action dispatching. Although, it is optional and it is not mandatory to have same name of this property. You can name it anything, but preferable is ‘<strong>payload</strong>’.</blockquote><pre>import { Action } from &quot;@ngrx/store&quot;;</pre><pre>import { Employee } from &quot;./employee.model&quot;;<br></pre><pre>export const ADD_EMPLOYEE = &quot;[Employee] Add Employee&quot;;</pre><pre>export const UPDATE_EMPLOYEE = &quot;[Employee] Update Employee&quot;;</pre><pre>export const DELETE_EMPLOYEE = &quot;[Employee] Delete Employee&quot;;</pre><pre>export class AddEmployee implements Action {</pre><pre>readonly type = ADD_EMPLOYEE;</pre><pre>constructor(public <em>payload</em>: Employee) {}</pre><pre>}</pre><pre>export class UpdateEmployee implements Action {</pre><pre>readonly type = UPDATE_EMPLOYEE;</pre><pre>constructor(</pre><pre>public <em>payload</em>: { id: string; empName: string; empProfile: string }</pre><pre>) {}</pre><pre>}</pre><pre>export class DeleteEmployee implements Action {</pre><pre>readonly type = DELETE_EMPLOYEE;</pre><pre>constructor(public <em>payload</em>: string) {}</pre><pre>}</pre><pre>export type EmployeeActions =</pre><pre>| AddEmployee</pre><pre>| UpdateEmployee</pre><pre>| DeleteEmployee</pre><blockquote><em>8. Add below lines of code into </em><strong>app/employee/employee.reducer.ts </strong><em>file.</em></blockquote><blockquote>We define our state or state data in reducer. In <strong>employeeReducer </strong>function we set our state with initial state value and action as <strong>EmployeeActions </strong>type (which we have created in <strong>app/employee/employee.actions.ts </strong>file).</blockquote><blockquote>When any action get dispatched, the action will pass into the second argument of reducer by store itself and reducer then will call appropriate action method on the basis of its (currently dispatched action) type and perform following functionality.</blockquote><blockquote>It then returns update the state and send the modified state to the store by itself.</blockquote><pre>import {</pre><pre>EmployeeActions,</pre><pre>ADD_EMPLOYEE,</pre><pre>UPDATE_EMPLOYEE,</pre><pre>DELETE_EMPLOYEE,</pre><pre>} from &quot;./employee.actions&quot;;</pre><pre>import { Employee } from &quot;./employee.model&quot;;</pre><pre>export interface empState {</pre><pre>employees: Employee[];</pre><pre>}</pre><pre>const intialState: empState = {</pre><pre>employees: [</pre><pre>new Employee(`EMP-${1}`, &quot;Employee 1&quot;, &quot;Dot Net Developer&quot;),</pre><pre>new Employee(`EMP-${2}`, &quot;Employee 2&quot;, &quot;Java Developer&quot;),</pre><pre>new Employee(`EMP-${3}`, &quot;Employee 3&quot;, &quot;Python Developer&quot;),</pre><pre>],</pre><pre>};</pre><pre>export function employeeReducer(</pre><pre><em>state</em>: empState = intialState,</pre><pre><em>action</em>: EmployeeActions</pre><pre>) {</pre><pre>switch (action.type) {</pre><pre>case ADD_EMPLOYEE:</pre><pre>return { ...state, employees: [...state.employees, action.payload] };</pre><pre>case UPDATE_EMPLOYEE:</pre><pre>return {</pre><pre>...state,</pre><pre>employees: state.employees.map((<em>x</em>) =&gt; {</pre><pre>if (x.id == action.payload.id) {</pre><pre>return {</pre><pre>id: x.id,</pre><pre>name: action.payload.empName,</pre><pre>profile: action.payload.empProfile,</pre><pre>};</pre><pre>} else {</pre><pre>return x;</pre><pre>}</pre><pre>}),</pre><pre>};</pre><pre>case DELETE_EMPLOYEE:</pre><pre>return {</pre><pre>...state,</pre><pre>employees: state.employees.filter((<em>x</em>) =&gt; x.id !== action.payload),</pre><pre>};</pre><pre>default:</pre><pre>return state;</pre><pre>}</pre><pre>}</pre><blockquote><em>9. Add below lines of code into </em><strong>app/app.reducer.ts </strong><em>file.</em></blockquote><blockquote>In here, we have defined our <strong>AppState</strong>. It tells us how our state will look like, when will fetch data from store.</blockquote><pre>import { ActionReducerMap } from &quot;@ngrx/store&quot;;</pre><pre>import { employeeReducer, empState } from &quot;./employees/employees.reducer&quot;;</pre><pre>export interface AppState {</pre><pre>employeesState: empState;</pre><pre>}</pre><pre>export const AppReducer: ActionReducerMap&lt;AppState&gt; = {</pre><pre>employeesState: employeeReducer</pre><pre>};</pre><blockquote><em>10. Add </em><strong>StoreModule </strong><em>from </em><strong>@ngrx/store </strong><em>and add into </em><strong>imports </strong><em>array. Also import </em><strong>AppReducer</strong><em> and set it inside the </em><strong>forRoot </strong><em>method of </em><strong>StoreModule</strong>.</blockquote><blockquote><strong>StoreModule</strong>’s here will set our state, which we defined in app reducer in previous step. Hereby, we have set our NgRx basic structure for our application.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ql12-E64eXZO7YX4Lgxdw.png" /></figure><blockquote><em>11. Now, go to </em><strong>app/employee/employee.component.html </strong><em>file and below html code.</em></blockquote><blockquote>In *ngFor, we are using async pipe on employees and then looping through the array to bind employees data.</blockquote><blockquote>While selecting state from store, the store will return an observable type state which further needed to fetch actual type of state in which our data is being stored.</blockquote><p>So async pipe will allow to wait to fetch actual type of state from store to bind employees data. In detail about observables, <a href="https://rxjs-dev.firebaseapp.com/guide/observable"><strong>click here</strong></a>.</p><pre>&lt;div class=&quot;container&quot;&gt;</pre><pre>&lt;div class=&quot;row&quot;&gt;</pre><pre>&lt;div class=&quot;col-xs-10&quot;&gt;</pre><pre>&lt;hr /&gt;</pre><pre>&lt;div class=&quot;form-group&quot;&gt;</pre><pre>&lt;input class=&quot;form-control&quot; placeholder=&quot;Enter Employee&#39;s Name&quot;</pre><pre>type=&quot;text&quot; #empName /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group&quot;&gt;</pre><pre>&lt;input class=&quot;form-control&quot; placeholder=&quot;Enter Employee&#39;s Profile&quot;</pre><pre>type=&quot;text&quot; #empProfile /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;button class=&quot;btn btn-primary&quot; title=&quot;add new employee&quot;(click)=&quot;isEdit ? updateEmployee() : addEmployee()&quot;&gt;</pre><pre>{{ !isEdit ? &quot;Add New Employee&quot; : &quot;Update Employee&quot; }}</pre><pre>&lt;/button&gt;</pre><pre>&lt;button *ngIf=&quot;isEdit&quot; class=&quot;btn btn-default&quot;(click)=&quot;onCancelEmployee()&quot;&gt;</pre><pre>Cancel</pre><pre>&lt;/button&gt;</pre><pre>&lt;button class=&quot;btn btn-warning&quot; (click)=&quot;fetchEmployees()&quot;&gt;</pre><pre>Fetch Employees</pre><pre>&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;row&quot;&gt;</pre><pre>&lt;div class=&quot;col-xs-10&quot;&gt;</pre><pre>&lt;hr /&gt;</pre><pre>&lt;table class=&quot;table table-hover&quot;&gt;</pre><pre>&lt;thead&gt;</pre><pre>&lt;tr&gt;</pre><pre>&lt;th scope=&quot;col&quot;&gt;#&lt;/th&gt;</pre><pre>&lt;th scope=&quot;col&quot;&gt;Employee ID&lt;/th&gt;</pre><pre>&lt;th scope=&quot;col&quot;&gt;Employee Name&lt;/th&gt;</pre><pre>&lt;th scope=&quot;col&quot;&gt;Employee Profile&lt;/th&gt;</pre><pre>&lt;th scope=&quot;col&quot;&gt;Actions&lt;/th&gt;</pre><pre>&lt;/tr&gt;</pre><pre>&lt;/thead&gt;</pre><pre>&lt;tbody&gt;</pre><pre>&lt;tr</pre><pre>*ngFor=&quot;</pre><pre>let employee of (employees | async).employees;</pre><pre>let i = index&quot;class=&quot;table-row-hover&quot;&gt;&lt;th scope=&quot;row&quot;&gt;{{ i + 1 }}&lt;/th&gt;</pre><pre>&lt;td&gt;{{ employee.id }}&lt;/td&gt;</pre><pre>&lt;td&gt;{{ employee.name }}&lt;/td&gt;</pre><pre>&lt;td&gt;{{ employee.profile }}&lt;/td&gt;</pre><pre>&lt;td&gt;</pre><pre>&lt;button class=&quot;btn btn-info&quot; (click)=&quot;editEmployee(employee)&quot;&gt;</pre><pre>Edit</pre><pre>&lt;/button&gt;</pre><pre>|&lt;button class=&quot;btn btn-danger&quot; (click)=&quot;onDelete(employee.id)&quot;&gt;</pre><pre>Delete</pre><pre>&lt;/button&gt;</pre><pre>&lt;/td&gt;</pre><pre>&lt;/tr&gt;</pre><pre>&lt;/tbody&gt;</pre><pre>&lt;/table&gt;</pre><pre>&lt;hr /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</pre><blockquote><em>12. Add below lines of code into </em><strong>app/employee/employee.component.ts </strong><em>file.</em></blockquote><blockquote>Initialize store in constructor, and set it with state which is type <strong>AppState </strong>in our application. Now select ‘<strong>employeeState</strong>’ type from store which is actual state of application in which we are managing our employees data.</blockquote><p>While selecting state from store, it will return an observable. So will take a property with same observable’s type and using it in html to bind employees data.</p><pre>import { Component, OnInit, ViewChild, ElementRef } from &quot;@angular/core&quot;;</pre><pre>import { Store } from &quot;@ngrx/store&quot;;</pre><pre>import { AppState } from &quot;../app.reducer&quot;;</pre><pre>import { Employee } from &quot;../employees/employee.model&quot;;</pre><pre>import { Observable } from &quot;rxjs&quot;;</pre><pre>import {</pre><pre>AddEmployee,</pre><pre>DeleteEmployee,</pre><pre>UpdateEmployee,</pre><pre>FetchEmployees,</pre><pre>} from &quot;../employees/employee.actions&quot;;<br></pre><pre>@Component({</pre><pre>selector: &quot;app-employee&quot;,</pre><pre>templateUrl: &quot;./employee.component.html&quot;,</pre><pre>styleUrls: [&quot;./employee.component.css&quot;],</pre><pre>})</pre><pre>export class EmployeeComponent implements OnInit {</pre><pre>employees: Observable&lt;{ employees: Employee[] }&gt;; <em>//employeeState: {employees: Employee[]}</em></pre><pre>@ViewChild(&quot;empName&quot;) empname: ElementRef;</pre><pre>@ViewChild(&quot;empProfile&quot;) empProfile: ElementRef;</pre><pre>isEdit: boolean = false;</pre><pre>currentEmpId: string;</pre><pre>constructor(private <em>store</em>: Store&lt;AppState&gt;) {}</pre><pre>ngOnInit() {</pre><pre>this.employees = this.store.select(&quot;employeesState&quot;); <em>// employeeState: {employees: Employee[]}</em></pre><pre>}</pre><pre>addEmployee() {</pre><pre>this.store.dispatch(</pre><pre>new AddEmployee( new Employee( `EMP-${Math.floor(Math.random() * 1001)}`, this.empname.nativeElement.value, this.empProfile.nativeElement.value)));</pre><pre>this.onCancelEmployee();</pre><pre>}</pre><pre>onDelete(<em>id</em>: string) {this.store.dispatch(new DeleteEmployee(id)); this.onCancelEmployee();}</pre><pre>editEmployee(<em>emp</em>: Employee) {</pre><pre>this.empname.nativeElement.value = emp.name;</pre><pre>this.empProfile.nativeElement.value = emp.profile;</pre><pre>this.isEdit = true;</pre><pre>this.currentEmpId = emp.id;</pre><pre>}</pre><pre>onCancelEmployee() {this.empname.nativeElement.value = &quot;&quot;; this.empProfile.nativeElement.value = &quot;&quot;; this.isEdit = false; this.currentEmpId = &quot;&quot;; }</pre><pre>updateEmployee() { <br>this.store.dispatch(new UpdateEmployee({id: this.currentEmpId, empName: this.empname.nativeElement.value, empProfile: this.empProfile.nativeElement.value, }));</pre><pre>this.onCancelEmployee();</pre><pre>}</pre><pre>fetchEmployees() {</pre><pre>// will talk about this later in effects</pre><pre>}</pre><pre>}</pre><blockquote><em>13. Add below css code into </em><strong>app/employee/employee.component.css<em> </em></strong><em>file.</em></blockquote><pre>.table-row-hover {cursor: pointer;}</pre><blockquote><em>14. Run below command in package console manager to start the application.</em></blockquote><pre>ng serve --open</pre><blockquote><em>15. It will start your application in browser and you can perform operations with such a clean and understandable structure of NgRx.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BIo1zwPizhPs-zA7VvyuA.png" /></figure><h3>Effects in NgRx</h3><blockquote>In above example, if you have run this code, you will see that there is a button <strong>Fetch Employees</strong>,<strong> </strong>which is currently doing nothing while clicking on it.</blockquote><blockquote>Here, what we are going to learn one more important feature provided by <strong>NgRx</strong> is <strong>Effects</strong>.</blockquote><h4><strong><em>Now what are Effects?</em></strong></h4><blockquote>Effects are long-running services that listen to an observable of <em>every</em> action dispatched from the store.</blockquote><blockquote>A typical effect uses the <strong>Actions</strong> Observable as its source and uses the <strong>ofType </strong>operator to perform its side effect when the corresponding action is dispatched.</blockquote><blockquote>Let’s make it more clear by creating our own effect into same application.</blockquote><blockquote><em>1. First of all add new file </em><strong>employee.effects.ts </strong><em>in </em><strong>app/employee </strong>folder.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*T31KavMO2AmnO_aLUOVfLA.png" /></figure><blockquote><em>2. Replace </em><strong>app/employee/employee.actions.ts </strong><em>with below lines of code.</em></blockquote><pre>import { Action } from &quot;@ngrx/store&quot;;</pre><pre>import { Employee } from &quot;./employee.model&quot;;</pre><pre>export const ADD_EMPLOYEE = &quot;[Employee] Add Employee&quot;;</pre><pre>export const UPDATE_EMPLOYEE = &quot;[Employee] Update Employee&quot;;</pre><pre>export const DELETE_EMPLOYEE = &quot;[Employee] Delete Employee&quot;;</pre><pre>export const  SET_EMPLOYEES = &quot;[Employee] Set Employee&quot;;</pre><pre>export const FETCH_EMPLOYEES = &quot;[Employee] Fetch Employees&quot;;</pre><pre>export class AddEmployee implements Action {</pre><pre>readonly type = ADD_EMPLOYEE;</pre><pre>constructor(public <em>payload</em>: Employee) {}</pre><pre>}</pre><pre>export class UpdateEmployee implements Action {</pre><pre>readonly type = UPDATE_EMPLOYEE;</pre><pre>constructor(</pre><pre>public <em>payload</em>: { id: string; empName: string; empProfile: string }</pre><pre>) {}</pre><pre>}</pre><pre>export class DeleteEmployee implements Action {</pre><pre>readonly type = DELETE_EMPLOYEE;</pre><pre>constructor(public <em>payload</em>: string) {}</pre><pre>}</pre><pre>export class FetchEmployees implements Action {</pre><pre>readonly type = FETCH_EMPLOYEES;</pre><pre>}</pre><pre>export class SetEmployees implements Action {</pre><pre>readonly type = SET_EMPLOYEES;</pre><pre>constructor(public <em>payload</em>: Employee[]) {}</pre><pre>}</pre><pre>export type EmployeeActions =</pre><pre>| AddEmployee</pre><pre>| UpdateEmployee</pre><pre>| DeleteEmployee</pre><pre>| FetchEmployees</pre><pre>| SetEmployees;</pre><blockquote><em>3. Replace </em><strong>app/employee/employee.reducer.ts </strong><em>with below lines of code.</em></blockquote><blockquote>Here, remove the static initialization of employees and set it as an empty array.</blockquote><blockquote>Will now fetch employees data using http service by implementing <strong>NgRx Effects</strong>.</blockquote><pre>import {</pre><pre>EmployeeActions,</pre><pre>ADD_EMPLOYEE,</pre><pre>UPDATE_EMPLOYEE,</pre><pre>DELETE_EMPLOYEE,</pre><pre>SET_EMPLOYEES,</pre><pre>} from &quot;./employee.actions&quot;;</pre><pre>import { Employee } from &quot;./employee.model&quot;;<br></pre><pre>export interface empState {</pre><pre>employees: Employee[];</pre><pre>}</pre><pre>const intialState: empState = {</pre><pre><em>// employees: [</em></pre><pre><em>//   new Employee(`EMP-${1}`, &quot;Employee 1&quot;, &quot;Dot Net Developer&quot;),</em></pre><pre><em>//   new Employee(`EMP-${2}`, &quot;Employee 2&quot;, &quot;Java Developer&quot;),</em></pre><pre><em>//   new Employee(`EMP-${3}`, &quot;Employee 3&quot;, &quot;Python Developer&quot;),</em></pre><pre><em>//   ],</em></pre><pre>employees: [],</pre><pre>};</pre><pre>export function employeeReducer(</pre><pre><em>state</em>: empState = intialState,</pre><pre><em>action</em>: EmployeeActions</pre><pre>) {</pre><pre>switch (action.type) {</pre><pre>case ADD_EMPLOYEE:</pre><pre>return { ...state, employees: [...state.employees, action.payload] };</pre><pre>case UPDATE_EMPLOYEE:</pre><pre>return {</pre><pre>...state,</pre><pre>employees: state.employees.map((<em>x</em>) =&gt; {</pre><pre>if (x.id == action.payload.id) {</pre><pre>return {</pre><pre>id: x.id,</pre><pre>name: action.payload.empName,</pre><pre>profile: action.payload.empProfile,</pre><pre>};</pre><pre>} else {</pre><pre>return x;</pre><pre>}</pre><pre>}),</pre><pre>};</pre><pre>case DELETE_EMPLOYEE:</pre><pre>return {</pre><pre>...state,</pre><pre>employees: state.employees.filter((<em>x</em>) =&gt; x.id !== action.payload),</pre><pre>};</pre><pre>case SET_EMPLOYEES:</pre><pre>return {</pre><pre>...state,</pre><pre>employees: action.payload,</pre><pre>};</pre><pre>default:</pre><pre>return state;</pre><pre>}</pre><pre>}</pre><blockquote><em>4. Add below lines of code in </em><strong>app/employee/employee.effects.ts </strong><em>file.</em></blockquote><blockquote>Here, <strong>fetchEmployees </strong>is an effect. The effect listens to every action that gets dispatched and when it retrieves an action with the action type <strong>FETCH_EMPLOYEES</strong>, it will make an HTTP request. Depending on the response the effect will either dispatch a <strong>SetEmployees </strong>action.</blockquote><pre>import { Effect, Actions, ofType } from &quot;@ngrx/effects&quot;;</pre><pre>import { Injectable } from &quot;@angular/core&quot;;</pre><pre>import { HttpClient } from &quot;@angular/common/http&quot;;</pre><pre>import { FETCH_EMPLOYEES, SetEmployees } from &quot;./employee.actions&quot;;</pre><pre>import { switchMap, map } from &quot;rxjs/operators&quot;;</pre><pre>import { Employee } from &quot;./employee.model&quot;;<br></pre><pre>@Injectable()</pre><pre>export class EmployeeEffects {</pre><pre>constructor(private <em>http</em>: HttpClient, private <em>actions</em>: Actions) {}</pre><pre>@Effect()</pre><pre>fetchEmployees = this.actions.pipe(</pre><pre>ofType(FETCH_EMPLOYEES),</pre><pre>switchMap(() =&gt; {</pre><pre>return this.http.get&lt;Employee[]&gt;(</pre><pre>&quot;https://ngrx-example-65f01.firebaseio.com/employees.json&quot;</pre><pre>);</pre><pre>}),</pre><pre>map((<em>employees</em>) =&gt; {</pre><pre>return new SetEmployees(employees);</pre><pre>})</pre><pre>);<br>}</pre><blockquote><em>5. Now add below lines of code inside the function </em><strong>fetchEmployees </strong><em>in </em><strong>app/employee/employee.component.ts </strong><em>file.</em></blockquote><pre>this.store.dispatch(new FetchEmployees());</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mgk09BRazxvkI4PPMVjPrA.png" /></figure><blockquote><em>6. Run it using command </em><strong>ng serve — open </strong><em>in package console manager.</em></blockquote><blockquote>Now we are familiar with the NgRx life-cycle. We also know that what is the role of effects while creating such reactive applications using NgRx structure.</blockquote><blockquote>Let’s take a look for other interesting features provided by NgRx.</blockquote><h3>Store-DevTools in NgRx</h3><blockquote>The NgRx DevTools are browser extension that includes a UI for inspecting and interacting with a NgRx based application.</blockquote><h4>Features/ benefits of S<strong>tore-DevTools</strong></h4><blockquote>1.<em> </em>The key benefit of the DevTools is that it provides us visual feedback about what the application is doing at all times, making it much easier to understand what is going on.</blockquote><blockquote>2. Gives us a great understanding of how the application works, and what parts of application are triggering which Actions.</blockquote><blockquote>3. A State inspector, allows us to easily inspect the in-memory store state.</blockquote><h4>Installation of Store-DevTools</h4><blockquote><em>1. Run below command in package console manager to install store-devtools package in your application.</em></blockquote><pre>npm install @ngrx/store-devtools --save</pre><blockquote><em>2. Go to </em><strong>src/app/app.module.ts<em> </em></strong><em>file.</em></blockquote><blockquote>Import <strong>StoreDevtoolsModule from </strong>@ngrx/store-devtools and set it into <strong>imports </strong>array.</blockquote><blockquote>Now call <strong>instrument </strong>method, which takes an object, in which we are going to define our configurations for <strong>DevTools</strong>.</blockquote><blockquote>For an example, here I have set <strong>logOnly </strong>property set to true for production build, which means it disables all extension features for production environment.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvGVovjHQ0cYGaQnuexE4A.png" /></figure><blockquote><em>3. Now search for </em><strong>Redux DevTools</strong><em> extension and install it into your browser.</em></blockquote><blockquote><em>4. After successfully installing it, run your application and open developer tools in browser. You will now able to access all features of NgRx in there.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*to_MEgMGSqJ-Bf4pPOofeg.png" /></figure><h3>Router-Store in NgRx</h3><blockquote><strong>NgRx Router Store </strong>provides binding which connects Angular router to Store. If you are working on some bigger reactive applications in which routing is also implemented. Here what NgRx Router Store comes with, without doing any extra efforts.</blockquote><blockquote>It simply uses the existing router navigation cycle and listens for changes router’s state, for each dispatched action, during this router navigation cycle.</blockquote><h4>Installation of Router-Store</h4><blockquote><em>1. Run below command in package console manager to install router-store in your application.</em></blockquote><pre>npm install @ngrx/router-store --save</pre><blockquote><em>2. Now go to </em><strong>src/app/app.module.ts </strong><em>file and import </em><strong>StoreRouterConnectingModule </strong><em>from </em>@ngrx/router-store.</blockquote><blockquote><em>Then, set into </em><strong>imports </strong><em>array and call </em><strong>forRoot </strong>method. That’s it, its hereby will automatically connects your existing Angular router to Store.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcYikut7wc79_KVJPEy2oQ.png" /></figure><h3>Error Handling</h3><blockquote>A very basic and most important part of our application is error handling. Error handling is something when some lines of code get would get break or some http service gets failed.</blockquote><blockquote>Here we will learn that how do we handle such exceptions using NgRx observables.</blockquote><blockquote>Let’s take an example with our application, where we will handle exception while our http service gets failed.</blockquote><blockquote><em>1. Add new action </em><strong>HANDLE_ERROR </strong><em>in </em><strong>app/employees/employee.action.ts </strong><em>file. And create new action class to define this action.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNbH84ihGLiOt3_x93S3pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSz2hqtx1LZ06PZecX66zQ.png" /></figure><blockquote><em>2. Now add a new case in </em><strong>app/employees/employees.reducer.ts </strong><em>file.</em></blockquote><blockquote>You can define your own error display logic. Here I am simply showing error message in alert box and returning the original state.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McjEMdH5q4VpC_L_8h48NQ.png" /></figure><blockquote><em>3. Add </em><strong>catchError </strong>(import from rxjs/operators)<em> just like below, in </em><strong>app/employees/employee.effects.ts<em> </em></strong><em>file.</em></blockquote><blockquote><strong>catchError<em> </em></strong><em>will return an observable and dispatch </em><strong>HandleError </strong><em>action to log or display the actual error.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AglPJY400cJw1rhmIw34Q.png" /></figure><blockquote>This is it!</blockquote><blockquote>So now we have learnt that how do we build reactive applications in Angular by implementing NgRx structure. Although, this is an short example just to understood that how NgRx life-cycle works, we can use this structure in bigger applications where we need state management on client side and perform other operations with our data and store back into a state.</blockquote><h3>Wrap Up</h3><ol><li>We have learnt about the state management in NgRx.</li><li>Understood the life-cycle of NgRx and what is the role of store, reducers and actions in complete life-cycle.</li><li>We discussed about NgRx Effects, Store-DevTools and Router-Store, which are great tools/ features provided by NgRx.</li><li>Last but not least, we have learnt about the error handling in NgRx Effects which will be really very helpful to manage our application and display meaningful error messages on UI.</li></ol><p><em>For more you can refer to </em><strong><em>https://ngrx.io/docs, </em></strong><em>to learn about updated tools/ features and their detailed information provided by NgRx officially.</em></p><p><a href="https://www.technossus.com/">Home</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4549d741c400" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>