19

Angular(v14) CRUD Example Using NgRx Data(v14)

 1 year ago
source link: https://www.learmoreseekmore.com/2022/07/angular14-crud-example-using-ngrx-data.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Let's%20reflect%20on%20what%20went%20well%20and%20what%20did%20not%20go%20well%20to%20improve%20the%20way%20we%20work..png

In this article, we are going to implement Angular(v14) CRUD operations using NgRX Data(v14) state management.

NgRx Data:

In general angular application uses NgRx store, effects, entity, etc libraries to maintain state. The trade-off with the '@ngrx/store' is we have to write a huge number of actions, reducers, effects, selectors, HTTP API calls per entity model, etc resulting in more numbers of files needing to be maintained.
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 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.
When to use NgRx Data?:
  • NgRx Data is a good choice when our application involves a lot of 'Create', 'Read', 'Update', 'Delete' operations.
  • Our Entity Model should contain a primary key value or unique key.
  • No requirement to interact with Ngrx libraries.
Most recommended way to use NgRx Data(@ngrx/data) along with NgRx Store(@ngrx/store) combination.
1.jpg
NgRx Data Flow:
  • Using NgRx Data we never contact the store directly, every store operation is carried out implicitly.
  • In NgRx Data our main point of contact to interact with the store is EntityCollectionService.
  • Using EntityCollectionService for each entity can invoke API calls with default methods like 'getAll()','add()', 'delete()', 'update()'.
  • So from our angular component, we need to invoke any one method from the 'EntityCollectionService'.
  • Then internally EntityActions gets triggered and raises the action method to invoke the API call base on our entity model.
  • On API success EntityAction raises a new action method to invoke the 'EntityCollectionReducers'.
  • So from the 'EntityCollectionReducer' appropriate reducer gets invoked and updates the data to store.
  • On stage change, selectors will fetch the data into the angular component from the store.

Create An Angular(14) Application:

Let's create an angular(14) application to accomplish our demo.
Command To Create Angular Application
ng new your_app_name
Install the bootstrap package
Command To Create Angular Application
npm install bootstrap
Configure Bootstrap CSS and JS files in 'angular.json'.
1.JPG

Add a bootstrap 'Navbar' component in 'app.component.html'
src/app/app.component.html:



  1. <nav class="navbar navbar-dark bg-warning">
  2. <div class="container-fluid">
  3. <div class="navbar-brand">Bakery Store</div>
  4. </div>
  5. </nav>

Setup JSON Server:

Let's set up a fake API by setting up the JSON server in our local machine.
Run the below command to install the JSON server globally onto your local machine.
npm install -g json-server
Now go to our angular application and add a command to run the JSON server into the 'package.json' file.
2.JPG

Now to invoke the above command, run the below command in the angular application root folder in a terminal window.

npm run json-run
After running the above command for the first time, a 'db.json' file gets created, so this file act as a database. So let's add some sample data in the 'db.json' file as below.
3.JPG
Now access the API endpoint like 'http://localhost:3000/cakes'.
4.JPG

Install NgRx Packages:

To implement NgRx Data we have to depend on 'NgRx Store', 'NgRx Effects', and 'NgRx Entity', so we have to install all those packages.
Command To Install NgRx Store
ng add @ngrx/store@latest
Command To Install NgRx Effects
ng add @ngrx/effects@latest
Command To Install NgRx Entity
ng add @ngrx/entity@latest
Command To Install NgRx Data
ng add @ngrx/data@latest
Command To Install NgRx DevTools
ng add @ngrx/store-devtools@latest
After installing the NgRx package, import the 'HttpClientModule' in 'AppModule'.
src/app/app.module.ts:


  1. import { HttpClientModule } from '@angular/common/http';
  2. // existing hidden for display purpose
  3. @NgModule({
  4. imports: [
  5. HttpClientModule
  6. export class AppModule { }

Create An Angular Feature Module(Ex: Cakes Module) And A Component(Ex: Home Component):

Let's create a Feature Module or Child Module. Run the below command to create.
ng generate module cakes --routing
5.JPG

Let's create the 'Home' component in the 'Cakes' module.

ng generate component cakes/home --skip-tests
6.JPG
In this demo, we will implement lazy loading. So let's configure routing for the 'Cakes' module to load lazily.
src/app/app-routing.module.ts:


  1. // existing code hidden for display purpose
  2. const routes: Routes = [{
  3. path:'',
  4. loadChildren: () => import("./cakes/cakes.module").then(_ => _.CakesModule)

Let's configure the route for the 'Home' component in the 'Cakes' routing module.

src/app/cakes/cakes-routing.module.ts:


  1. import { HomeComponent } from './home/home.component';
  2. // existing code hidden for display purpose
  3. const routes: Routes = [
  4. path: '',
  5. component: HomeComponent,

Create A Model And A Entity Metadata In Cake Module(Feature/Child Module):

NgRx data depends on the Model or Entity which is the type for the data to be stored. Each model must be registered in the 'Entity MetaData'.
Let's create a 'Cakes' Model in our Feature Module(Cake Module).
ng generate interface cakes/store/cakes

src/app/cakes/store/cakes.ts:



  1. export interface Cakes {
  2. id: number;
  3. name: string;
  4. description: string;
  5. cost: number;

Let's create an Entity Meta Data for our Feature Module(Cake Module) like 'cakes-entity-metadata.ts'.

src/app/cakes/store/cake-entity-metadata.ts:


  1. import { EntityMetadataMap } from "@ngrx/data";
  2. import { Cakes } from "./cakes";
  3. export const cakesEntityMetaData: EntityMetadataMap = {
  4. Cake:{
  5. selectId:(cake:Cakes) => cake.id
  • Here 'EntityMetadataMap' loads from the '@ngrx/data'. Here we have to register all the entity models(eg: Cakes) that are related to our feature module(eg: Cakes module).
  • (Line: 5) Here defined the entity name like 'Cake'. This name plays a very crucial role in our NgRx data. By pluralizing the entity name like 'Cakes' then NgRx Data will generate the URLs of our API with plural names.
  • 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.
Now register the 'cookieEntityMetaData' in 'CookiesModule'.
src/app/cookies/cookies.module.ts:


  1. import { EntityDefinitionService } from '@ngrx/data';
  2. import { cakesEntityMetaData } from './store/cakes-entity-metadata';
  3. @NgModule({
  4. declarations: [HomeComponent],
  5. imports: [CommonModule, CakesRoutingModule],
  6. export class CakesModule {
  7. constructor(entityDefinitionService: EntityDefinitionService) {
  8. entityDefinitionService.registerMetadataMap(cakesEntityMetaData);
  • Here using 'EntityDefinitionService' registered our 'cakesEntityMetaData'.

EntityCollectionService:

An EntityCollectionService is the main tool for the NgRx data to handle the 'dispatcher' and 'selector$' 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 update 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.

Implement Read Operation:

Let's implement the read operation which means invoking the API call, saving the API response into the store, and then reading the data from the store.
Let's update the logic in 'home.component.ts' as below
src/app/cakes/home/home.component.ts:


  1. import { Component, OnInit } from '@angular/core';
  2. import {
  3. EntityCollectionService,
  4. EntityCollectionServiceFactory,
  5. } from '@ngrx/data';
  6. import { Observable } from 'rxjs';
  7. import { Cakes } from '../store/cakes';
  8. @Component({
  9. selector: 'app-home',
  10. templateUrl: './home.component.html',
  11. styleUrls: ['./home.component.css'],
  12. export class HomeComponent implements OnInit {
  13. constructor(serviceFactory: EntityCollectionServiceFactory) {
  14. this.cakeService = serviceFactory.create<Cakes>('Cake');
  15. this.allCakes$ = this.cakeService.entities$;
  16. allCakes$: Observable<Cakes[]>;
  17. cakeService: EntityCollectionService<Cakes>;
  18. ngOnInit(): void {
  19. this.cakeService.getAll();
  • (Line: 15) Here injected the 'EntityCollectionServiceFactory' that loads from the '@ngrx/data'.
  • (Line: 16) Creating the instance of 'EntityCollectionService' from the 'EntityCollectionServiceFactory'. Here we used the name 'Cake' this name is nothing but the property name that we registered in the 'cakesEntityMetaData'.
  • (Line: 17) Here 'EntityCollectionService.entities$' observable fetches the data that was stored in the NgRx store.
  • (Line: 20) Here declared the 'allCakes$' variable which is of type 'Observable<Cakes[]>'.
  • (Line: 21) Here declared the 'cakeService' variable which is of type 'EntityCollectionService<Cakes>'.
  • (Line: 24) The 'EntityCollectionService.getAll()' is a default HTTP get method that will implicitly frame URL based property name(eg: 'Cake') in 'cakeEntityMetaData', implicitly invokes the actions, 'effects', 'reducer' to generate the state based on the API repsonse. 

src/app/cakes/home/home.component.html:



  1. <div class="container mt-2">
  2. <div class="row row-cols-1 row-cols-md-3 g-4">
  3. <div class="col" *ngFor="let cake of allCakes$ | async">
  4. <div class="card">
  5. <div class="card-body">
  6. <h5 class="card-title">{{ cake.name }}</h5>
  7. <ul class="list-group list-group-flush">
  8. <li class="list-group-item">Price: {{ cake.cost }}</li>
  9. </ul>
  10. </div>
  11. <div class="card-body">
  12. <p>{{ cake.description }}</p>
  13. </div>
  14. </div>
  15. </div>
  16. </div>
  17. </div>

Now if we run the application API call will fail because the auto-generated API URL by NgRx Data is "http://localhost:4000/api/cakes/", but the actual API URL is "http://locast:3000/cakes". To update the API URL we have to implement the DefultHttpURLGenerator service.

Let's create a service that implements DefaultHttpURLGenerator.
ng generate class shared/store/customurl-http-generator --skip-tests

src/app/shared/store/customurl-http-generator.ts:



  1. import { Injectable } from '@angular/core';
  2. import { DefaultHttpUrlGenerator, HttpResourceUrls, Pluralizer } from '@ngrx/data';
  3. @Injectable()
  4. export class CustomurlHttpGenerator extends DefaultHttpUrlGenerator {
  5. constructor(pluralizer: Pluralizer) {
  6. super(pluralizer);
  7. protected override getResourceUrls(
  8. entityName: string,
  9. root: string,
  10. trailingSlashEndpoints?: boolean
  11. ): HttpResourceUrls {
  12. let resourceURLs = this.knownHttpResourceUrls[entityName];
  13. if (entityName == 'Cake') {
  14. resourceURLs = {
  15. collectionResourceUrl: 'http://localhost:3000/cakes/',
  16. entityResourceUrl: 'http://localhost:3000/cakes/',
  17. this.registerHttpResourceUrls({ [entityName]: resourceURLs });
  18. return resourceURLs;
  • (Line: 4) Extending the 'DefaultHttpUrlGenerator' that loads from the '@ngrx/data'
  • (Line: 9) Overriding the 'getResourURLS'
  • Here based on the 'entityName' we replacing the API URL. Here 'entityName' is nothing but the property name in the 'cakeEntityMetaData'.

Now register the 'CustomUrlHttpGenerator' in 'AppModule'.

src/app/app.module.ts:


  1. import { EntityDataModule, HttpUrlGenerator } from '@ngrx/data';
  2. import { CustomurlHttpGenerator } from './shared/store/customurl-http-generator';
  3. // existing code hidden for display purpose
  4. @NgModule({
  5. providers: [
  6. provide: HttpUrlGenerator,
  7. useClass: CustomurlHttpGenerator,
  8. export class AppModule { }

Now we can observe data get rendered.

7.JPG

Create 'Add' Component:

Let's create a new component like 'Add' at the 'Cakes' module.
ng generate component cakes/add --skip-tests
Let's configure the 'Add' component routing in 'CakeRoutingModule'.
src/app/cakes/cakes-routing.module.ts:


  1. import { AddComponent } from './add/add.component';
  2. // exisiting code removed for display purpose
  3. const routes: Routes = [
  4. path: 'add',
  5. component: AddComponent

Implementing Create Operation:

Let's implement the 'Create' operation using NgRx Data.
Let's update the logic in the 'Add' component as below.
src/app/cakes/add/add.component.ts:


  1. import { Component, OnInit } from '@angular/core';
  2. import { Router } from '@angular/router';
  3. import { EntityCollectionService, EntityCollectionServiceFactory } from '@ngrx/data';
  4. import { Cakes } from '../store/cakes';
  5. @Component({
  6. selector: 'app-add',
  7. templateUrl: './add.component.html',
  8. styleUrls: ['./add.component.css']
  9. export class AddComponent implements OnInit {
  10. constructor(
  11. serviceFactory: EntityCollectionServiceFactory,
  12. private router: Router
  13. this.cakeService = serviceFactory.create<Cakes>('Cake');
  14. cakeService: EntityCollectionService<Cakes>;
  15. cakeForm: Cakes = {
  16. id: 0,
  17. description: '',
  18. name: '',
  19. cost: 0,
  20. ngOnInit(): void {}
  21. save() {
  22. this.cakeService.add(this.cakeForm).subscribe(() => {
  23. this.router.navigate(['/']);
  • (Line: 14) Injected the 'EntityCollectionServiceFactory' that loads from the '@ngrx/data'
  • (Line: 15) Injected the 'Router' service that loads from the '@angular/router'.
  • (Line: 17) Creating the 'EntityCollectionService' instance using 'EntityCollectionServiceFactory'. Here service name 'Cake' is the property name in 'cakeEntityMetaData'.
  • (Line: 19) Declared 'cakeService' variable of type 'EntityCollectionService'.
  • (Line: 21-26) The 'cakeForm' variable binds with angular form.
  • (Line: 31-33) The 'EntiyCollectionService.add()' method invokes the HTTP Post call to create a item at server.

src/app/cakes/add/add.component.html:



  1. <div class="container">
  2. <legend>Add A New Cake</legend>
  3. <div class="mb-3">
  4. <label for="txtName" class="form-label">Name of Cake</label>
  5. <input
  6. type="text"
  7. [(ngModel)]="cakeForm.name"
  8. class="form-control"
  9. id="txtName"
  10. />
  11. </div>
  12. <div class="mb-3">
  13. <label for="txtdescription" class="form-label">Description</label>
  14. <textarea
  15. type="text"
  16. [(ngModel)]="cakeForm.description"
  17. class="form-control"
  18. id="txtdescription"
  19. ></textarea>
  20. </div>
  21. <div class="mb-3">
  22. <label for="txtCost" class="form-label">Cost</label>
  23. <input
  24. type="number"
  25. [(ngModel)]="cakeForm.cost"
  26. class="form-control"
  27. id="txtCost"
  28. />
  29. </div>
  30. <button type="button" class="btn btn-warning" (click)="save()">Create</button>
  31. </div>

Let's import the 'FormsModule' in the 'CakesModule'.

src/app/cakes/cakes.module.ts:


  1. import { FormsModule } from '@angular/forms';
  2. // existing code hidden for display purpose
  3. @NgModule({
  4. imports: [FormsModule],
  5. export class CakesModule {
  6. constructor(entityDefinitionService: EntityDefinitionService) {
  7. entityDefinitionService.registerMetadataMap(cakesEntityMetaData);
In 'home.component.html' add the 'Add A New Cake' button.
src/app/cakes/home/home.component.html:
<div class="row">
<div class="col col-md4 offset-md-4">
  <a routerLink="/add" class="btn btn-warning">Add A New Book</a>
</div>
</div>

(step:1)

8.JPG
(step 2)
9.JPG

Create 'Edit' Component:

Let's create a new component like 'Edit' at the 'Cake' module.
ng generate component cakes/edit --skip-tests
Let's add the 'Edit' component route to the 'Cake' module.


  1. import { EditComponent } from './edit/edit.component';
  2. const routes: Routes = [
  3. path: 'edit/:id',
  4. component: EditComponent
  • Here ':id' represents the dynamic value part of the path.

Implement Update Operation:

Let's implement the update operation using the NgRx Data.
Let's update the logic in the 'Edit' component as below.
src/app/cakes/edit/edit.component.ts:


  1. import { Component, OnInit } from '@angular/core';
  2. import { ActivatedRoute, Router } from '@angular/router';
  3. import { EntityCollectionService, EntityCollectionServiceFactory } from '@ngrx/data';
  4. import { combineLatest } from 'rxjs';
  5. import { Cakes } from '../store/cakes';
  6. @Component({
  7. selector: 'app-edit',
  8. templateUrl: './edit.component.html',
  9. styleUrls: ['./edit.component.css']
  10. export class EditComponent implements OnInit {
  11. constructor(
  12. serviceFactory: EntityCollectionServiceFactory,
  13. private router: Router,
  14. private route: ActivatedRoute
  15. this.cakeService = serviceFactory.create<Cakes>('Cake');
  16. cakeService: EntityCollectionService<Cakes>;
  17. cakeForm: Cakes = {
  18. id: 0,
  19. description: '',
  20. name: '',
  21. cost: 0,
  22. ngOnInit(): void {
  23. let fetchFormData$ = combineLatest([
  24. this.route.paramMap,
  25. this.cakeService.entities$,
  26. ]).subscribe(([params, cakes]) => {
  27. var id = Number(params.get('id'));
  28. var filteredCake = cakes.filter((_) => _.id == id);
  29. if (filteredCake) {
  30. this.cakeForm = { ...filteredCake[0] };
  31. update() {
  32. this.cakeService.update(this.cakeForm).subscribe(() => {
  33. this.router.navigate(["/"]);
  • (Line: 31-40) Here 'combineLatest' that load from the 'rxjs'. The 'combineLatest' executes with the latest output from all observables registered inside of it. Here we fetch the item 'id' value from the URL and filter it against the store data to populate it on the edit form.
  • (Line: 43) The 'EntityCollectionService.update()' is used to invoke the HTTP PUT API call to update the data at the server.
Let's add the 'Edit' button to the 'app.component.html'.
src/app/app.component.html:


  1. <div class="card-body">
  2. <a class="btn btn-warning" [routerLink]="['/edit', cake.id]">Edit</a> |
  3. </div>
  • Here generating the 'edit' button URL dynamically by adding the 'id' value.

Step1:

10.JPG

Step2:

11.JPG

Step3:

12.JPG

Implement Delete Operation:

Let's implement the delete operation using the NgRx data.
Let's update the 'home.component.ts' as below.
src/app/cakes/home/home.component.ts: 


  1. import { Component, OnInit } from '@angular/core';
  2. import {
  3. EntityCollectionService,
  4. EntityCollectionServiceFactory,
  5. } from '@ngrx/data';
  6. import { Observable } from 'rxjs';
  7. import { Cakes } from '../store/cakes';
  8. declare var window: any;
  9. @Component({
  10. selector: 'app-home',
  11. templateUrl: './home.component.html',
  12. styleUrls: ['./home.component.css'],
  13. export class HomeComponent implements OnInit {
  14. constructor(serviceFactory: EntityCollectionServiceFactory) {
  15. this.cakeService = serviceFactory.create<Cakes>('Cake');
  16. this.allCakes$ = this.cakeService.entities$;
  17. allCakes$: Observable<Cakes[]>;
  18. cakeService: EntityCollectionService<Cakes>;
  19. deleteModal: any;
  20. idToDelete: number = 0;
  21. ngOnInit(): void {
  22. this.deleteModal = new window.bootstrap.Modal(
  23. document.getElementById('deleteModal')
  24. this.cakeService.getAll();
  25. openDeleteModal(id: number) {
  26. this.idToDelete = id;
  27. this.deleteModal.show();
  28. confirmDelete() {
  29. this.cakeService.delete(this.idToDelete)
  30. .subscribe((data) => {
  31. this.deleteModal.hide();
  • (Line: 9) Declare the window instance.
  • (Line: 25) The 'deleteModal' variable is declared to assign the instance of the bootstrap modal.
  • (Line: 26) The 'idToDelete' variable to store the item to delete.
  • (Line: 29-31) The instance of the bootstrap is assigned to the 'deleteModal'.
  • (Line: 36-39) The 'openDeleteModal' opens the popup to display the delete confirmation. The 'show()' method opens the bootstrap modal.
  • (Line: 41-46) The 'EntityCollectionServices.delete()' method invokes the HTTP delete API call.

src/app/cakes/home/home.component.html:



  1. <div class="container mt-2">
  2. <div class="row">
  3. <div class="col col-md4 offset-md-4">
  4. <a routerLink="/add" class="btn btn-warning">Add A New Book</a>
  5. </div>
  6. </div>
  7. <div class="row row-cols-1 row-cols-md-3 g-4">
  8. <div class="col" *ngFor="let cake of allCakes$ | async">
  9. <div class="card">
  10. <div class="card-body">
  11. <h5 class="card-title">{{ cake.name }}</h5>
  12. <ul class="list-group list-group-flush">
  13. <li class="list-group-item">Price: {{ cake.cost }}</li>
  14. </ul>
  15. </div>
  16. <div class="card-body">
  17. <p>{{ cake.description }}</p>
  18. </div>
  19. <div class="card-body">
  20. <a class="btn btn-warning" [routerLink]="['/edit', cake.id]">Edit</a> |
  21. <button type="button" class="btn btn-danger" (click)="openDeleteModal(cake.id)">
  22. Delete
  23. </button>
  24. </div>
  25. </div>
  26. </div>
  27. </div>
  28. </div>
  29. <div
  30. class="modal fade"
  31. id="deleteModal"
  32. tabindex="-1"
  33. aria-labelledby="exampleModalLabel"
  34. aria-hidden="true"
  35. <div class="modal-dialog">
  36. <div class="modal-content">
  37. <div class="modal-header">
  38. <h5 class="modal-title" id="exampleModalLabel">Delete Confirmation</h5>
  39. <button
  40. type="button"
  41. class="btn-close"
  42. data-bs-dismiss="modal"
  43. aria-label="Close"
  44. ></button>
  45. </div>
  46. <div class="modal-body">Are you sure to delete this item?</div>
  47. <div class="modal-footer">
  48. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
  49. Close
  50. </button>
  51. <button type="button" class="btn btn-danger" (click)="confirmDelete()">
  52. Confirm Delete
  53. </button>
  54. </div>
  55. </div>
  56. </div>
  57. </div>
  • (Line: 21-23) The 'Delete' button click event registered with 'openDeleteModal()' method.
  • (Line: 30-51) Delete confirmation popup modal HTML.
13.JPG

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on the Angular 14 State Management CRUD example with NgRx(14) Data. using I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK