Introduction:
NgRx framework helps Angular to develop more reactive applications. NgRx provides state management to an application, where data of an application is stored at a single place and then supplied throughout the application where ever needed. Using NgRx if data is updated, all the components consuming that data get updated instantly.
Benefits of using NgRx with Angular application like Serializability, Type Safety, Encapsulation, Testable, and Performance.
Key Features:
NgRx framework key features like
- Store: A store is a data place where all the application related information stored and supplied to the Angular components on demand.
- Reducer: A reducer is a pure function based on Actions it returns the new state.
- Actions: An action expresses an event of an application, that causes a change in the state of the application.
- Selector: A selector is a pure function that obtains a slice of data from the store.
- Effects: An Effect is to isolate components from using services(APIs) and with the help actions and reducers change the state of the store.
Note: NgRx store version 8+ using in this sample, there are some new features are added and implementation style was changed from v8+ when compare to v7 and below.
Create An Angular Project:
Let's create a sample to show items in a Bakery Shop. So first create the angular project using Angular CLI commands. Click here for Angular CLI commands.
Install @ngrx/store:
Open the command prompt by taking package.json file in the sample project physical location as a reference path. Now to use NgRx framework run the following NPM command
"npm install @ngrx/store --save"
Now in a package.json observe as below
"npm install @ngrx/store --save"
Now in a package.json observe as below
Actions:
NgRx Actions represents the event expression of an application. It represents what to happen and how to happen the changes in an application. Based on Action dispatches NgRx Store or NgRx Effects get triggered.
export interface Action { type: string; }NgRx Action is a simple interface having only one property 'type', this 'type' property is like a name or identification or role of that particular NgRx Action. Since it is an interface we need to implement it to use it. But Ngrx Store provides the predefined function to create and use NgRx action.
import {createAction} from '@ngrx/store'; export const getStudents = createAction( '[Student] load all students' )
- Here 'createAction' is a predefined function provided by the NgRx Store and it is an overloaded function.
- The parameter passed to 'createAction' is a 'type' property of the action, if we observe from the type property this action will trigger an event to load all students from API or NgRx Store.
- '[Student]' this just namespace or naming convention to represent the NgRx Action type.
import {createAction ,props} from '@ngrx/store'; export const getNewsByRange = createAction( '[News] load news by date values', props<{startDate:string, endDate:string}>() )
- Here 'createAction' is another overloaded function with two parameters.
- 'props<T>()' is a function defined by NgRx Store, this function gives the possibility to pass query parameters of action.
- In the above action method, it represents the loading of news information with specified date ranges as a query filter to the news data
Create Actions:
Our sample application to show bakery items, let us start code to display cakes in a bakery. Now create folder name as 'store', then create another folder named 'cakes' and now create an action file name as cake.action.ts in the 'store/cakes/' folder.
cakes.action.ts :
import {createAction} from '@ngrx/store'; export const loadCakes = createAction( '[Cakes] load' )Here action represents to load all cakes.
Reducers:
Reducer is a pure function their goal is like the same output every time for the given input. Reducers take two input params like Action and State. 'State' is just a JSON object which stores the data and based on the action type reducer returns the new state to the angular components. This Reducer gets invoked by the store dispatch which will discuss in later.
import {Action, createReducer, on,createAction} from '@ngrx/store'; const loadSomething = createAction( 'load' ) export interface State { data:any[] } export const initialState: State = { data:[] } const loadReducer = createReducer(initialState, on(loadSomething,state => { const newState =state; newState.data.push(0); return state; }) ); export function reducer(state: State| undefined,action :Action){ return loadReducer(state, action); }
- 'State' can be imagined as a database in the serverside language. It is to store and deliver the data on demand.
- 'initialState' is like default empty state at the time no data exist in the store.
- Reducer function takes state and action as input params. In version 7 or below inside reducer we wrote code like switch case with return new state, but from NgRx v8+ we returning 'createReducer' function which takes two parameters like state and function.
- In 'createReducer' second parameter is an arrow function where we can write logic to create a new state and give it back to the application.
- The reason we always create a new state and return, due Redux(NgRx framework build on top of Redux) principals that reducers are a pure function that is immutable and only return a new state.
Create a Cake Model and Cake State Model:
Models make coding good by providing 'TypeSafety' to it, so whenever possible where ever needed alway create models. Now in this sample, let us create the folder 'model' and inside add files like 'model.ts' which contains all application-related models and 'store.model.ts' which contains all NgRx Store, related models.
model.ts:
export interface Cake{ Id:number; CakeName:string; Image:string; Cost:number; }store.model.ts:
import {Cake} from './model' export interface CakeState { SuccessMessage:string; ErrorMessage:string; Data:Cake[] }
Create Reducer:
Create a file at 'stores/cakes' and name as 'cakes.reducer.ts'
import { Action, createReducer, on } from "@ngrx/store"; import {loadCakes} from './cakes.action'; import { CakeState } from "../../models/stores.model"; export const initialState:CakeState ={ Data : [], SuccessMessage : '', ErrorMessage: '' } const cakeReducer = createReducer( initialState, on(loadCakes, state => { return { ...state }; }) ) export function reducer(state: CakeState | undefined, action: Action){ return cakeReducer(state, action); }
- Here 'initialState' is like default state.
- 'cakeReducer' is 'createReducer' function here we taking the first parameter as 'State' and the second parameter is 'on' function provided by NgRxStore.
- 'on' function overloaded function here we are taking the first parameter action 'loadCake' and the second parameter is arrow function where the state as input parameter here we can create new state using current state and return the state(later steps we will update this 'cakeReducers' with the different set Actions).
Selectors:
Selectors are also pure functions used to get a slice of data from the NgRx store. Selectors represent query methods. Using selectors it isolates or avoids writing data filtering or data modification code in the angular components.
import {createFeatureSelector, createSelector} from '@ngrx/store' export interface BookState{ Id:number, Name: string, } export interface OrdersState { Id:number, CustomerName:string } export interface AppState{ books:BookState, orders:OrdersState } export const selectBooks = createFeatureSelector<appstate,Bookstate>('books'); export const selectOrders = createFeatureSelector<appstate,ordersstate>('orders'); export const selectBookName = createSelector(selectBooks, state => state.Name); export const selectOrderId = createSelector(selectOrders, state => state.Id);
- In the above example 'BookState', 'OrderState' represents two different stores.
- In general, all the store states are maintained under one state can name as 'AppState'(can be called as the application state).
- NgRx provides 'createFeatureSelector' it gives a particular state in an application based input parameter.
- 'createFeatureSelect' expects the string parameter whose value need to exactly match with 'AppState' property name like 'books' and 'orders'.
- Here 'selectBooks' represents 'BookState' and 'selectOrders' represents 'OrderState'.
- NgRx provides 'createSelector' gets inside data of an 'State'. Here 'selectBookName' represents a collection of book name and 'selectOrders' represents a collection of order ids.
Create Selectors:
Create a file for selectors at a path '/stores' and name the file as 'store.selectors.ts'
import {createFeatureSelector, createSelector} from '@ngrx/store' import { CakeState } from "../models/stores.model"; export interface AppState { cake:CakeState } export const selectCakeState = createFeatureSelector<appstate,cakestate>('cake'); export const selectAllCakes = createSelector(selectCakeSate, state => state.Data);
- Here we have created 'AppState' which encapsulates all other States in the application. 'selectCakeState' holds the 'CakeState' with the help 'createFeatureSelector'. 'createFeatureSelector' takes 'cake' as input parameter, this 'cake' string should match with property name 'AppState'.
- 'selectAllCakes' is a state which represents a collection of 'Cake' with the help of 'createSelector' provided by NgRx Store
Create A Service:
Now in the 'assets' folder add a new file name as cake.json in that file mock some cake items. In real-time we are going to consume API instead of a mock JSON file
Create a service folder as 'app/services' in that add a new file 'cake.service.ts'. It is an injectable service that calls cakes.json file using angular Httpclient.import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import{map} from "rxjs/operators"; @Injectable() export class CakeService { constructor(private http: HttpClient) {} get(){ return this.http.get("./assets/cakes.json").pipe(map(data=> data["AllCakes"])) } }
Effects:
In an Angular Application creates injectable services to consume APIs. We access those services by injecting them into our components to display the data from API. Instead of injecting services into the components we can achieve the same functionality by using NgRx Effects. By using the Effects we can isolate services from components.
Effects are like events that occur out of the application and are not consumed by components directly like we do for services. Effects are triggered based on action dispatched from the store, once the effect gets activated it calls API and pushes the data to the store.
import {Injectable} from '@angular/core'; import {Actions,createEffect, ofType} from '@ngrx/effects'; import {of} from 'rxjs' import {mergeMap, map, catchError} from 'rxjs/operators' @Injectable() export class SomeEffects{ constructor(private actions$:Actions){ } loadSomething$ = createEffect(() => this.actions$.pipe( ofType('[Something] load Something'), mergeMap(() => of('In real time here api call observable will be used') .pipe( map(data => ({type:'[Something] load Something Successfully',payload:data})), catchError(() => of({type:'[Something] load Something Failed'})) )) ) ) }
- 'createEffect' is provided by the NgRx store to create an effect like 'loadSomething$'. 'createEffect' takes a function as an input parameter, this input parameter function returns observable.
- 'Actions' is provided by the NgRx Effects. 'Actions' is an observable type, it gets invoked on every action dispatched from the store in angular components.
- 'Actions' are injected into effects services, since it is observable here we listen to the action using 'pipe' operator. 'OfType' in NgRx Effects filters the action by matching the action type (like '[Something] load Something') with the action type dispatched from the store, if both types of actions match effects goes further execution else effect will be stoped. This says 'OfType' helps to execute the appropriate Effects.
- Then listen to the inner observable of API call inside of 'mergeMap' RXJS operators. Finally on the successful execution of inner observable returns observable object of action type and payload data or if inner observable fails returns observable object of an action. This observable result will be available to the NgRx store for changing its state.
Install Effects:
Ngrx shifts effects separate package so run the following command
npm install @ngrx/effects --save
Create An Effect:
Now add Effects file in 'src/stores/cakes/' and name as 'cakes.effects.ts'
import { Injectable } from "@angular/core"; import { Actions, createEffect, ofType } from "@ngrx/effects"; import { of } from "rxjs"; import { mergeMap, map, catchError } from "rxjs/operators"; import { CakeService } from "../../services/cake.service"; @Injectable() export class SomeEffects { constructor(private actions$: Actions, private cakeService:CakeService) {} loadCakes$ = createEffect(() => this.actions$.pipe( ofType('[Cakes] load'), mergeMap( () => this.cakeService.get() .pipe( map(data => ({type:'[Cakes] successful cakes load',cakes:data})), catchError(eror => of({type:'[Cakes] fails cakes load'})) )) ) ); }
- 'Actions' from NgRx effects and CakeService are injected into this effects service.
- 'loadCakes$' creates an effect using 'createEffect()'. 'ofType('[Cakes] load')' it represent this effect only triggered for '[Cakes] load' action.
- On successful API call return Observable of the object literal with keys like 'type' and 'cake' (this 'cakes' name should match with the action props method like props<{cakes: Cake[]}>). On failed API call return Observable of the object literal with key 'type'. This Observable object will be passed to the store based on action types passed in the key 'type' and then the store creates a new state.
Create Actions For API Success And Fail:
In previous steps, we have created the '[Cakes] load' action. Now we need to update the 'cakes.action.ts' file with 2 more actions
export const successCakeLoad = createAction( '[Cakes] successful cakes load', props<{cakes:Cake[]}>() ); export const failsCakeLoad = createAction( '[Cakes] fails cakes load' )
Update Reducer To Change Store State Based On API Success Or Fail Actions:
Now update the 'cake.reducer.ts' which changes the state of the store based on the action methods.
import { Action, createReducer, on } from "@ngrx/store"; import * as cakesAction from './cakes.action'; import { CakeState } from "../../models/stores.model"; export const initialState:CakeState ={ Data : [], SuccessMessage : '', ErrorMessage: '' } const cakeReducer = createReducer( initialState, on(cakesAction.successCakeLoad, (state, {cakes}) => { return { ...state, Data : cakes, SuccessMessage : 'Success', ErrorMessage:'' } }), on(cakesAction.failsCakeLoad, state => { return { ...state, Data:[], SuccessMessage:'', ErrorMessage:'failed' } }) ) export function reducer(state: CakeState | undefined, action: Action){ return cakeReducer(state, action); }
- On 'cakeAction.successCakeLoad' action represents API success, here create a new state with the payload from the API and SuccessMessage property update with some success message
- On 'cakeAction.failsCakeLoad' action represents API fails, here create new state with empty data and ErrorMessage property updated with some error message
Access Data From NgRx Store:
Let save API data to store and access it from the angular component. Now create a new component at 'src/cakes' and name as cakes.component.ts
import {Component, OnInit} from '@angular/core'; import {Store, select} from '@ngrx/store'; import {CakeState} from '../models/stores.model' import * as cakeActions from '../stores/cakes/cakes.action'; import * as storeSelectors from '../stores/store.selectors'; import {Cake} from '../models/model' @Component({ selector:'cakes', templateUrl:'cake.component.html' }) export class CakeComponent implements OnInit { allCakes:Cake[]; constructor(private store:Store<storeSelectors.AppState>){ } ngOnInit(){ this.store.pipe(select(storeSelectors.selectAllCakes)).subscribe(data => { this.allCakes = data; }); this.store.dispatch(cakeActions.loadCakes()); } }
- In the constructor inject store like 'Store<storeSelectors.AppState>', by doing this we have access to the store with all states that are used in the application this happened because store type is 'AppState'.
- AppState is an application state which holds all other individual stores states. In our application, we created only one state 'CakeState', which resides inside the 'AppState'.
- In ngOnInit, we dispatch the action 'cakeActions.loadCakes()'. In an application on dispatching an action will automatically trigger all the 'NgRx Effects' get invoked, but the only Effect gets executed which matches the action dispatched. If we recall the above steps we have created NgRx Effect with action name 'loadCakes'.
- In ngOnInit, we registered a store subscription with the NgRx Selector 'selectAllCakes'. This subscription gets invoked on every update of the store. Herewith 'selecAllCakes' selector going to query all the cakes from the store.
<h1>Cake Bite</h1> <div class="row"> <div class="col col-sm-4" *ngFor="let cake of allCakes"> <div class="card"> <img src="/assets/{{cake.Image}}" class="card-img-top" alt=""> </div> <div class="card-body"> <h5 class="card-title">{{cake.CakeName}}</h5> <div class="row"> <div class="col col-sm-6"> Cost </div> <div class="col col-sm-6"> $ {{cake.Cost}} </div> </div> </div> </div> </div>
Update NgRx Store & NgRx Effects Module In AppMoudle:
Final step update NgRx Store and NgRx Effects modules in AppModule file
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {StoreModule} from '@ngrx/store'; import {EffectsModule} from '@ngrx/effects'; import {HttpClientModule} from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import {CakeComponent} from './cakes/cake.component'; import * as cakeReducer from './stores/cakes/cakes.reducer'; import {CakeEffects} from './stores/cakes/cakes.effect'; import {CakeService} from './services/cake.service'; @NgModule({ declarations: [ AppComponent, CakeComponent ], imports: [ BrowserModule, HttpClientModule, StoreModule.forRoot({cake:cakeReducer.reducer}), EffectsModule.forRoot([CakeEffects]), AppRoutingModule ], providers: [CakeService], bootstrap: [AppComponent] }) export class AppModule { }
- 'StoreModule.forRoot({})' is NgRx Store modules, we need to register all our application reducer function like key-value pair object in the module
- 'EffectsModule.forRoot([])' is NgRx Effects modules, we need to register all our application effects like an array of objects in the module.
Test Sample Application:
Summary:
A successful sample application was created using NgRx Store. Using the NgRx Store Statemangement of an application becomes a very essay. Since NgRx Effects isolate services from the angular component, it makes angular components very lightweight and logic free. Data sharing between components will become very flexible.
Comments
Post a Comment