In this article, we are going to implement an Angular application state management using @ngrx/data.
Ngrx Store Flow:
Now add the Bootstrap menu in the 'app.component.html'
@ngrx/data:
In a general angular application using NgRx Store, Effects, and Entity libraries made us to write a huge number of actions, reducers, effects, selectors, HTTP API calls per entity model. It leads to a lot of repetitive code to create, maintain and test.
Using NgRx Data we can reduce our code to very little despite having a large number of entity models in our application. The NgRx Data is an abstraction over the Store, Effects, and Entity that radically reduces the amount of code we have to write. By gaining the abstraction benefit, we are going to lose our direct interaction with NgRx libraries.
- Using Ngrx we never contact the store directly, every store operation is carried out by the NgRx store implicitly.
- Our main point of contact is EntityCollectionService.
- Using EntityCollectionService for each entity can invoke API calls with default method like 'getAll()', 'add()', 'delete()', 'update()'.
- So from our angular component, we need to invoke any one method from the 'EntityCollectionService'. Then internally EntityAction gets triggered and raises an action method to invoke the API call based on our entity model.
- On API success EntityAction raises a new action method to invoke 'EntityCollectionReducers'.
- So from the 'EntityCollectionReducer' appropriate reducer gets invoked and updates the data to store.
- On state change, selectors will fetch the data into the angular component from the store.
Create An Angular Application:
To start our demo let's create an angular sample application. While creating a sample make sure to enable routing because in this demo we are going to implement lazy loading as well.
Install Angular CLI:
npm install -g @angular/cli
npm install -g @angular/cli
Command To Create Angular Application:
ng new your-project-name
ng new your-project-name
Let's create a new module like 'shop' for our demo. Run the below command to create module and route files.
ng g module shop --routing
Let's add components like 'products'. Run the below command to generated component files.
ng g component shop/products
Now let's define the route.
app/shop/shop-routing.module.ts:
import { ProductsComponent } from './products/products.component'; const routes: Routes = [ { path:'', component: ProductsComponent }, ];app/app-routing.module.ts:
const routes: Routes = [{ path:'', loadChildren:() => import('./shop/shop.module').then(_ => _.ShopModule) }];
Install Bootstrap And Configure Menu:
npm install bootstrap
Include the Bootstrap CSS and js files into the 'angular.json' file
Now add the Bootstrap menu in the 'app.component.html'
app/app.component.html:
<nav class="navbar navbar-expand-lg bg-dark"> <div class="container-fluid"> <a href="#" class="navbar-brand text-white"> Shopping </a> </div> </nav>
Install And Configure @ngrx/data:
Now let's install '@ngrx/data' and its dependent libraries.
Command To Install Store:
npm install @ngrx/store --save
npm install @ngrx/store --save
Command To Install Effects:
npm install @ngrx/effects --save
npm install @ngrx/effects --save
Command To Install NgRx Entity:
npm install @ngrx/entity --save
npm install @ngrx/entity --save
Command To Install NgRx Data:
npm install @ngrx/data --save
npm install @ngrx/data --save
Command To Install Dev Tool(Optional):
npm install @ngrx/store-devtools --save
npm install @ngrx/store-devtools --save
Now let's import the required modules into the 'AppModule'.
app/app.module.ts:
import { HttpClientModule } from '@angular/common/http'; import { EntityDataModule } from '@ngrx/data'; import { EffectsModule } from '@ngrx/effects'; import { StoreModule } from '@ngrx/store'; import { StoreDevtoolsModule } from '@ngrx/store-devtools'; import { environment } from 'src/environments/environment'; // existing code hidden for display purpose @NgModule({ imports: [ AppRoutingModule, HttpClientModule, StoreModule.forRoot({}), EffectsModule.forRoot([]), EntityDataModule.forRoot({}), StoreDevtoolsModule.instrument({ maxAge: 25, // Retains last 25 states logOnly: environment.production, // Restrict extension to log-only mode autoPause: true, // Pauses recording actions and state changes when the extension window is not open }) ] }) export class AppModule { }
- Important note the 'EntityDataModule' must register after 'StoreModule' and 'EffectsModule'.
- Also notice HttpClientModule also imported
- The 'StoreDevToolsModule' for enabling the chrome extension debugger for our store.
Register Entity Models Into Entity MetaData:
Let's first create the response model from my API endpoint. Create a 'product.model.ts' in the 'shop/products' folder.
app/shop/products/product.model.ts:
export interface ProductModel { productId: number; name: string; manufacturer: string; description: string; price: number; }To use NgRx Data all our application models should be registered within Entity MetaData. Since I'm using a module-based application let's create a new file in 'shop' folder like 'shop-entity-metadata.ts'.
app/shop/shop-entity-metadata.ts:
import { EntityMetadataMap } from "@ngrx/data"; import { ProductModel } from "./products/product.model"; export const shopEntityMetaData:EntityMetadataMap ={ Product:{ selectId: (prodcut:ProductModel) => prodcut.productId, /* Options props ================== filterFn, sortComparer, etc */ } }
- Here 'EtntiyMetadataMap' loads from the '@ngrx/data'. Here we have to register all the entity models here.
- (Line: 5) Here defined the entity name like 'Product'. This name plays a very crucial role in our NgRx data. By pluralizing the entity name like 'Products' NgRx Data will generate the URLs of our API.
- In general, our entity model should contain the primary key property mostly 'Id' to work with NgRx Data. By default 'Id' property will be recognized by the Ngrx Data, but if we want to specify our custom property as the primary key then we have to use the 'selectId' property like above.
- Along with 'selectId' property, EntityMetadataMap provides so many different props, so explore them if needed.
app/shop/shop.modulet.ts:
import { EntityDefinitionService } from '@ngrx/data'; import { shopEntityMetaData } from './shop-entity-metadata'; /* code hidden for disply purpose */ @NgModule({ }) export class ShopModule { constructor(entityDefinitionService: EntityDefinitionService) { entityDefinitionService.registerMetadataMap(shopEntityMetaData); } }
- Here registering our Entity MetaData with the help of 'EntityDefinitionService' injecting into the module constructor.
Use EntityCollectionService:
An EntityCollectionService is a main tool for the NgRx data to handle the 'distpacher' and 'selectors$' that manages an entity collection cached in the NgRx store.
The 'Dispatcher' features a command method that dispatches entity actions to the Ngrx store. So these dispatcher commands can update the store directly or invoke the HTTP request. In case of invoking HTTP requests, on successful response again new action will be invoked to updates the entity collection in the store.
The 'Dispatcher' features a command method that dispatches entity actions to the Ngrx store. So these dispatcher commands can update the store directly or invoke the HTTP request. In case of invoking HTTP requests, on successful response again new action will be invoked to updates the entity collection in the store.
The 'selectors$' are properties returning selector observables. Each observable watches for a specific change in the cached entity collection and emits the changed value.
Now in our component let's use EntityCollectionService to use all NgRx Data features.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core'; import { EntityCollectionService, EntityCollectionServiceFactory, } from '@ngrx/data'; import { Observable } from 'rxjs'; import { ProductModel } from './product.model'; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.css'], }) export class ProductsComponent implements OnInit { allProducts$: Observable<ProductModel[]>; productService: EntityCollectionService<ProductModel>; constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) { this.productService = entityCollectionServiceFactory.create<ProductModel>("Product"); this.allProducts$ = this.productService.entities$; } ngOnInit(): void { this.productService.getAll(); } }
- (Line: 15) The 'allProducts$' variable of type 'Observable<ProductModel[]>'. This variable holds data that need to be bind to the UI.
- (Line: 16) The 'productService' variable of type 'EntityCollectionService<ProductModel>'. This variable represents our 'Product' entity collection. This variable will be our key to interact with the EntityCollection of our store. Using the 'EntityCollectionService' we can use predefined 'dispatchers' and 'selectors$' to communicate with the store.
- (Line: 17) Injecting the 'EntityCollectionServiceFactory' that loads from the '@ngrx/data'.
- (Line: 18&19) Using 'EntityCollectionServiceFactory', we will create instance of 'EntityCollectionService' of type 'Products. To do that we have to use a name like 'Product'(This name must match with one of the property names of the 'EntityMetadataMap')
- (Line: 20) The 'entities$' is one of the EntityCollectionService 'selectors$'.
- (Line: 24) The 'getAll()' is one of the EntityCollectionService 'dispatcher'.
<div class="container"> <div class="row"> <table class="table table-dark table-striped m-3"> <thead> <tr> <th scope="col">Product Id</th> <th scope="col">Name</th> <th scope="col">Manufacturer</th> <th scope="col">Description</th> <th scope="col">Price</th> </tr> </thead> <tbody> <tr *ngFor="let item of allProducts$ | async"> <th scope="row">{{item.productId}}</th> <td>{{item.name}}}</td> <td>{{item.manufacturer}}</td> <td>{{item.description}}</td> <td>{{item.price}}</td> </tr> </tbody> </table> </div> </div>
- Binding the data from the variable 'allProducts$'.
Implement DefaultHttpUrlGenerator:
Now to configure my API domain we are going to implement DefaultHttpUrlGenerator. But one disadvantage in this approach, if our API is like 'http://localhost:5000/api/products' then the same URL will be used for all HTTP requests like GET, POST, PUT, DELETE(How to overcome this disadvantage can be explored in upcoming steps).
So now in the 'app' folder let's create a new file like 'custom-url-http-general-generator.service.ts'.
app/custom-url-http-general-generator.service.ts:
import { Injectable } from '@angular/core'; import { DefaultHttpUrlGenerator, HttpResourceUrls, Pluralizer, } from '@ngrx/data'; @Injectable({ providedIn: 'root', }) export class CustomUrlHttpGeneralGeneratorService extends DefaultHttpUrlGenerator { constructor(private myPluralizer: Pluralizer) { super(myPluralizer); } protected getResourceUrls( entityName: string, root: string ): HttpResourceUrls { let resourceUrls = this.knownHttpResourceUrls[entityName]; if (entityName == 'Product') { const url = 'https://localhost:44324/api/Products/'; resourceUrls = { entityResourceUrl: url, collectionResourceUrl: url, }; this.registerHttpResourceUrls({ [entityName]: resourceUrls }); } return resourceUrls; } }
- Here service gets executed for every 'dispatcher' method of 'EntityCollectionService'. So here based on the entity name we are overriding the URL.
app/app.module.ts:
import { EntityDataModule, HttpUrlGenerator } from '@ngrx/data'; import { CustomUrlHttpGeneralGeneratorService } from './custom-url-http-general-generator.service'; // code hidden for display purpose @NgModule({ providers: [ { provide: HttpUrlGenerator, useClass: CustomUrlHttpGeneralGeneratorService } ] }) export class AppModule { }Now run the application again and can see the output like below.
Add Operation:
Now we are going to explore the 'Add Operation' behavior with NgRx Data.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core'; import { EntityCollectionService, EntityCollectionServiceFactory, } from '@ngrx/data'; import { Observable } from 'rxjs'; import { ProductModel } from './product.model'; declare var window: any; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.css'], }) export class ProductsComponent implements OnInit { allProducts$: Observable<ProductModel[]>; productService: EntityCollectionService<ProductModel>; myModal: any; productForm: ProductModel = { description: '', manufacturer: '', name: '', price: 0, productId: 0, }; modalTitle:string = '' constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) { this.productService = entityCollectionServiceFactory.create<ProductModel>('Product'); this.allProducts$ = this.productService.entities$; } ngOnInit(): void { this.productService.getAll(); this.myModal = new window.bootstrap.Modal( document.getElementById('productsModal'), { keyboard: false, } ); } openModal(productId: number) { if (productId == 0) { this.modalTitle = "Add Product"; this.productForm = { description: '', manufacturer: '', name: '', price: 0, productId: 0, }; } this.myModal.show(); } saveorupdate() { if (this.productForm.productId == 0) { this.productService.add(this.productForm).subscribe(_ => this.myModal.hide()); } } }
- (Line: 8) The 'window' instance is declared.
- (Line: 18) The 'myModal' variable to store the instance of the Bootstrap Modal.
- (Line: 19-25) The 'productForm' variable to maintain the form data for to add or update.
- (Line: 26) The 'modalTitle' variable for Bootstrap Modal title.
- (Line: 35-40) Assigning the instance of the Bootstrap Modal popup to 'myModal' variable.
- (Line: 43-53) The 'OpenModal()' method going to be used for opening the Modal popup form. This method will be commonly used for both 'Add' and 'Update' operations.
- (Line: 59) Invoking 'add()' method from 'EntityCollectionService'. So 'add()' method invokes the API call and on success, API call the new record will be added to EntityCollection of the store.
<div class="container"> <div class="row m-1"> <div class="col text-center"> <button type="button" class="btn btn-primary" (click)="openModal(0)"> Add Product </button> </div> </div> <div class="row"> <table class="table table-dark table-striped m-2"> <!-- code hidden for display purspose --> </table> </div> </div> <!-- Modal --> <div class="modal fade" id="productsModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body"> <div class="container"> <input type="hidden" id="productId" [(ngModel)]="productForm.productId"> <div class="row"> <div class="mb-3"> <label for="name" class="form-label">Product Name</label> <input type="text" class="form-control" id="name" [(ngModel)]="productForm.name"/> </div> </div> <div class="row"> <div class="mb-3"> <label for="manufacturer" class="form-label">Manufacturer</label> <input type="text" class="form-control" id="manufacturer"[(ngModel)]="productForm.manufacturer" /> </div> </div> <div class="row"> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label" >Description</label > <input type="text" class="form-control" id="description" [(ngModel)]="productForm.description" /> </div> </div> <div class="row"> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label" >Price</label > <input type="text" class="form-control" id="price" [(ngModel)]="productForm.price" /> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" > Close </button> <button type="button" class="btn btn-primary" (click)="saveorupdate()">Save changes</button> </div> </div> </div> </div> </div>
- (Line: 4-6) The 'Add' button, its click event registered with 'openModal()' method.
- Rendered Bootstrap Modal that contains form fields enabled angular 2-way binding.
- (Line: 75) The 'Save Changes' button, its click event registered with 'saveorupdate()' method.
Update Operation:
Now let's try to explore update operation.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core'; import { EntityCollectionService, EntityCollectionServiceFactory, } from '@ngrx/data'; import { Observable } from 'rxjs'; import { ProductModel } from './product.model'; declare var window: any; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.css'], }) export class ProductsComponent implements OnInit { allProducts$: Observable<ProductModel[]>; productService: EntityCollectionService<ProductModel>; myModal: any; productForm: ProductModel = { description: '', manufacturer: '', name: '', price: 0, productId: 0, }; modalTitle: string = ''; constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) { this.productService = entityCollectionServiceFactory.create<ProductModel>('Product'); this.allProducts$ = this.productService.entities$; } ngOnInit(): void { this.productService.getAll(); this.myModal = new window.bootstrap.Modal( document.getElementById('productsModal'), { keyboard: false, } ); } openModal(productId: number) { if (productId == 0) { this.modalTitle = 'Add Product'; this.productForm = { description: '', manufacturer: '', name: '', price: 0, productId: 0, }; } else { this.modalTitle = 'Update Product'; this.productService.entities$.subscribe((data) => { let filteredProduct = data.filter((_) => _.productId == productId)[0]; this.productForm = {...filteredProduct}; }); } this.myModal.show(); } saveorupdate() { if (this.productForm.productId == 0) { this.productService .add(this.productForm) .subscribe((_) => this.myModal.hide()); } else { this.productService .update(this.productForm) .subscribe((_) => this.myModal.hide()); } } }
- (Line: 54) Set the title for the modal popup.
- (Line: 55-58) Filtering the product to be updated from 'entitis$' store selector. Result assigned to 'productForm' variable.
- (Line: 69-71) Used 'update' dispatcher method of EntityServiceCollection.
app/shop/products/products.component.html:
<!-- code hidden for display purpose --> <div class="container"> <div class="row"> <table class="table table-dark table-striped m-2"> <thead> <tr> <th scope="col">Product Id</th> <th scope="col">Name</th> <th scope="col">Manufacturer</th> <th scope="col">Description</th> <th scope="col">Price</th> <th scope="col">Actions</th> </tr> </thead> <tbody> <tr *ngFor="let item of allProducts$ | async"> <td> <button class="btn btn-primary" (click)="openModal(item.productId)">Edit</button> </td> </tr> </tbody> </table> </div> </div>
- (Line: 18) Enabled 'Edit' button for each record, this button register with a click event method like 'openModal()'
Delete Operation:
Let's explore the delete option here.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core'; import { EntityCollectionService, EntityCollectionServiceFactory, } from '@ngrx/data'; import { Observable } from 'rxjs'; import { ProductModel } from './product.model'; declare var window: any; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.css'], }) export class ProductsComponent implements OnInit { allProducts$: Observable<ProductModel[]>; productService: EntityCollectionService<ProductModel>; myModal: any; productForm: ProductModel = { description: '', manufacturer: '', name: '', price: 0, productId: 0, }; modalTitle: string = ''; productIdToDelete :number = 0; deleteModal:any; constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) { this.productService = entityCollectionServiceFactory.create<ProductModel>('Product'); this.allProducts$ = this.productService.entities$; } ngOnInit(): void { this.productService.getAll(); this.myModal = new window.bootstrap.Modal( document.getElementById('productsModal'), { keyboard: false, } ); this.deleteModal = new window.bootstrap.Modal( document.getElementById('deleteModal'), { keyboard: false, } ) } openModal(productId: number) { if (productId == 0) { this.modalTitle = 'Add Product'; this.productForm = { description: '', manufacturer: '', name: '', price: 0, productId: 0, }; } else { this.modalTitle = 'Update Product'; this.productService.entities$.subscribe((data) => { let filteredProduct = data.filter((_) => _.productId == productId)[0]; this.productForm = {...filteredProduct}; }); } this.myModal.show(); } saveorupdate() { if (this.productForm.productId == 0) { this.productService .add(this.productForm) .subscribe((_) => this.myModal.hide()); } else { this.productService .update(this.productForm) .subscribe((_) => this.myModal.hide()); } } openDeleteModal(productId: number){ this.productIdToDelete = productId; this.deleteModal.show(); } delete(){ this.productService.delete(this.productIdToDelete) .subscribe(_ => this.deleteModal.hide()); } }
- (Line: 27) The 'productIdToDelete' variable holds the record primary key that needs to be deleted.
- (Line: 28) The 'deleteModal' variable is used to assign the Bootstrap Modal instance.
- (Line: 43-48) Created the instance of the Bootstrap Modal and assigned it to the 'deleteModal' variable.
- (Line: 83-86) The 'openDeleteModal' method to display the Bootstrap Modal for the delete confirmation.
- (Line: 87-90) The 'delete()' dispatcher of EntityCollectionService used to delete the records.
<!-- Code Hidden For Display Purpose --> <div class="container"> <div class="row"> <table class="table table-dark table-striped m-2"> </thead> <tbody> <tr *ngFor="let item of allProducts$ | async"> <button class="btn btn-primary" (click)="openModal(item.productId)">Edit</button> <button class="btn btn-danger" (click)="openDeleteModal(item.productId)">Delete</button> </td> </tr> </tbody> </table> </div> </div> <!-- Modal --> <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <h4>Confirm To Delete</h4> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" (click)="delete()">Delete</button> </div> </div> </div> </div>
- (Line: 11) The 'Delete' button registered with click event 'OpenDeleteModal'.
- (Line: 20-36) Delete confirmation popup.
- (Line: 32) The 'Delete' confirmation button registered with click event like 'delete()'.
Implement DefaultDataService<T>:
The '@ngrx/data' provides us a service like 'DefaultDataService<T>'. Using 'DefaultDataService<T>' we can override the default HTTP call methods like 'getAll()', 'add()', 'update()', 'delete()'. It helps to define our custom API URL and also allows us to modify the response data before saving into the EntityCollection of the store.
For our demo purpose, I will override the 'getAll()' method and also set the 'Price' value to '0' before saving it into the store. Let's create a service file like 'product.data.service.ts' in the 'products' folder.
app/shop/products/product.data.service.ts:
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { DefaultDataService, HttpUrlGenerator } from '@ngrx/data'; import { Observable } from 'rxjs'; import { ProductModel } from './product.model'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class ProductDataService extends DefaultDataService<ProductModel> { constructor(http: HttpClient, httpUrlGenerator: HttpUrlGenerator) { super('Product', http, httpUrlGenerator); } getAll(): Observable<ProductModel[]> { return this.http.get('https://localhost:44324/api/Products/').pipe( map((data) => { if (!data) { return []; } return (data as ProductModel[]).map((d) => { return { ...d, price: 0 }; }); }) ); } }
- (Line: 11) Our service class 'ProductDataService' extends 'DefaultDataService<T>' that loads from '@ngrx/data'.
- (Line: 13) To the base class passing 'Product'(name of the entity), 'http'(instance of the HTTPClient), 'httpUrlGenerator'(instance of the HttpUrlGenerator).
- (Line: 16-27) Overriding the 'getAll()' method.
- (Line: 17) Defined our full API URL.
- (Line: 22-24) Modifying the API response data like 'Price' value set to '0'.
app/shop/shop.module.ts:
import { EntityDataService, EntityDefinitionService } from '@ngrx/data'; import { ProductDataService } from './products/product.data.service'; // code hidden for display purpose @NgModule({ }) export class ShopModule { constructor( entityDefinitionService: EntityDefinitionService, entitydataService: EntityDataService, productDataService:ProductDataService ) { entityDefinitionService.registerMetadataMap(shopEntityMetadata); entitydataService.registerService('Product', productDataService); } }
- (Line: 13) Registered the 'ProductDataService' with the entity name 'Product'.
That's all about implementing '@ngrx/data' into the angular application.
Video Session:
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on Ngrx Data(Version 12). I love to have your feedback, suggestions, and better techniques in the comment section below.
API Not working
ReplyDeleteapi/Products is missing can you share same repo
ReplyDeleteIt is my local running .net core api. It is not under angular reposity
DeleteShare the API Code also bro
DeleteCan you share the API bro
ReplyDeleteHi Naveen, Excellent article and youtube video. Got stuck on implementing it though. I get the following run-time error in the console 'httpUrlGenerator.registerHttpResourceUrls is not a function'.
ReplyDeleteThanks.
Just as an FYI. I'm using strict mode. Not sure whether that would cause the issue.
ReplyDeleteI tried to get this to run locally, but without a backend API working, it fails. I think you should either post the code to run the API locally or make a note at the beginning of this article that this is not meant to be run on your local machine because there is no functioning API available.
ReplyDelete