Skip to main content

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

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.

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'.

Add a bootstrap 'Navbar' component in 'app.component.html'
src/app/app.component.html:
<nav class="navbar navbar-dark bg-warning">
  <div class="container-fluid">
    <div class="navbar-brand">Bakery Store</div>
  </div>
</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.

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.

Now access the API endpoint like 'http://localhost:3000/cakes'.

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:
import { HttpClientModule } from '@angular/common/http';
// existing hidden for display purpose
@NgModule({
  imports: [
    HttpClientModule
  ]
})
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


Let's create the 'Home' component in the 'Cakes' module.
ng generate component cakes/home --skip-tests


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:
// existing code hidden for display purpose
const routes: Routes = [{
  path:'',
  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:
import { HomeComponent } from './home/home.component';
// existing code hidden for display purpose
const routes: Routes = [
  {
    path: '',
    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:
export interface Cakes {
  id: number;
  name: string;
  description: string;
  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:
import { EntityMetadataMap } from "@ngrx/data";
import { Cakes } from "./cakes";

export const cakesEntityMetaData: EntityMetadataMap = {
    Cake:{
        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:
import { EntityDefinitionService } from '@ngrx/data';
import { cakesEntityMetaData } from './store/cakes-entity-metadata';

@NgModule({
  declarations: [HomeComponent],
  imports: [CommonModule, CakesRoutingModule],
})
export class CakesModule {
  constructor(entityDefinitionService: EntityDefinitionService) {
    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:
import { Component, OnInit } from '@angular/core';
import {
  EntityCollectionService,
  EntityCollectionServiceFactory,
} from '@ngrx/data';
import { Observable } from 'rxjs';
import { Cakes } from '../store/cakes';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  constructor(serviceFactory: EntityCollectionServiceFactory) {
    this.cakeService = serviceFactory.create<Cakes>('Cake');
    this.allCakes$ = this.cakeService.entities$;
  }

  allCakes$: Observable<Cakes[]>;
  cakeService: EntityCollectionService<Cakes>;

  ngOnInit(): void {
    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:
<div class="container mt-2">
  <div class="row row-cols-1 row-cols-md-3 g-4">
    <div class="col" *ngFor="let cake of allCakes$ | async">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">{{ cake.name }}</h5>
          <ul class="list-group list-group-flush">
            <li class="list-group-item">Price: {{ cake.cost }}</li>
          </ul>
        </div>
        <div class="card-body">
          <p>{{ cake.description }}</p>
        </div>
      </div>
    </div>
  </div>
</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:
  
import { Injectable } from '@angular/core';
import { DefaultHttpUrlGenerator, HttpResourceUrls, Pluralizer } from '@ngrx/data';
@Injectable()
export class CustomurlHttpGenerator extends DefaultHttpUrlGenerator {
  constructor(pluralizer: Pluralizer) {
    super(pluralizer);
  }

  protected override getResourceUrls(
    entityName: string,
    root: string,
    trailingSlashEndpoints?: boolean
  ): HttpResourceUrls {
    let resourceURLs = this.knownHttpResourceUrls[entityName];
    if (entityName == 'Cake') {
      resourceURLs = {
        collectionResourceUrl: 'http://localhost:3000/cakes/',
        entityResourceUrl: 'http://localhost:3000/cakes/',
      };
      this.registerHttpResourceUrls({ [entityName]: resourceURLs });
    }
    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:
import { EntityDataModule, HttpUrlGenerator } from '@ngrx/data';
import { CustomurlHttpGenerator } from './shared/store/customurl-http-generator';
// existing code hidden for display purpose
@NgModule({

  providers: [
    {
      provide: HttpUrlGenerator,
      useClass: CustomurlHttpGenerator,
    },
  ]
})
export class AppModule { }
Now we can observe data get rendered.

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:
import { AddComponent } from './add/add.component';
// exisiting code removed for display purpose
const routes: Routes = [
  {
    path: 'add',
    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:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { EntityCollectionService, EntityCollectionServiceFactory } from '@ngrx/data';
import { Cakes } from '../store/cakes';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {

  constructor(
    serviceFactory: EntityCollectionServiceFactory,
    private router: Router
  ) {
    this.cakeService = serviceFactory.create<Cakes>('Cake');
  }
  cakeService: EntityCollectionService<Cakes>;

  cakeForm: Cakes = {
    id: 0,
    description: '',
    name: '',
    cost: 0,
  };

  ngOnInit(): void {}

  save() {
    this.cakeService.add(this.cakeForm).subscribe(() => {
      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:
<div class="container">
  <legend>Add A New Cake</legend>
  <div class="mb-3">
    <label for="txtName" class="form-label">Name of Cake</label>
    <input
      type="text"
      [(ngModel)]="cakeForm.name"
      class="form-control"
      id="txtName"
    />
  </div>
  <div class="mb-3">
    <label for="txtdescription" class="form-label">Description</label>

    <textarea
      type="text"
      [(ngModel)]="cakeForm.description"
      class="form-control"
      id="txtdescription"
    ></textarea>
  </div>
  <div class="mb-3">
    <label for="txtCost" class="form-label">Cost</label>
    <input
      type="number"
      [(ngModel)]="cakeForm.cost"
      class="form-control"
      id="txtCost"
    />
  </div>
  <button type="button" class="btn btn-warning" (click)="save()">Create</button>
</div>
Let's import the 'FormsModule' in the 'CakesModule'.
src/app/cakes/cakes.module.ts:
import { FormsModule } from '@angular/forms';
// existing code hidden for display purpose
@NgModule({
  imports: [FormsModule],
})
export class CakesModule {
  constructor(entityDefinitionService: EntityDefinitionService) {
    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)

(step 2)

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.
import { EditComponent } from './edit/edit.component';

const routes: Routes = [
  {
    path: 'edit/:id',
    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:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { EntityCollectionService, EntityCollectionServiceFactory } from '@ngrx/data';
import { combineLatest } from 'rxjs';
import { Cakes } from '../store/cakes';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

  constructor(
    serviceFactory: EntityCollectionServiceFactory,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.cakeService = serviceFactory.create<Cakes>('Cake');
  }
  cakeService: EntityCollectionService<Cakes>;

  cakeForm: Cakes = {
    id: 0,
    description: '',
    name: '',
    cost: 0,
  };

  ngOnInit(): void {
    let fetchFormData$ = combineLatest([
      this.route.paramMap,
      this.cakeService.entities$,
    ]).subscribe(([params, cakes]) => {
      var id = Number(params.get('id'));
      var filteredCake = cakes.filter((_) => _.id == id);
      if (filteredCake) {
        this.cakeForm = { ...filteredCake[0] };
      }
    });
  }
  update() {
    this.cakeService.update(this.cakeForm).subscribe(() => {
      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:
<div class="card-body">
  <a class="btn btn-warning" [routerLink]="['/edit', cake.id]">Edit</a> |
</div>
  • Here generating the 'edit' button URL dynamically by adding the 'id' value.
Step1:
Step2:
Step3:

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: 
import { Component, OnInit } from '@angular/core';
import {
  EntityCollectionService,
  EntityCollectionServiceFactory,
} from '@ngrx/data';
import { Observable } from 'rxjs';
import { Cakes } from '../store/cakes';

declare var window: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  constructor(serviceFactory: EntityCollectionServiceFactory) {
    this.cakeService = serviceFactory.create<Cakes>('Cake');
    this.allCakes$ = this.cakeService.entities$;
  }

  allCakes$: Observable<Cakes[]>;
  cakeService: EntityCollectionService<Cakes>;

  deleteModal: any;
  idToDelete: number = 0;

  ngOnInit(): void {
    this.deleteModal = new window.bootstrap.Modal(
      document.getElementById('deleteModal')
    );

    this.cakeService.getAll();
  }

  openDeleteModal(id: number) {
    this.idToDelete = id;
    this.deleteModal.show();
  }

  confirmDelete() {
    this.cakeService.delete(this.idToDelete)
    .subscribe((data) => {
      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:
<div class="container mt-2">
  <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>
  <div class="row row-cols-1 row-cols-md-3 g-4">
    <div class="col" *ngFor="let cake of allCakes$ | async">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">{{ cake.name }}</h5>
          <ul class="list-group list-group-flush">
            <li class="list-group-item">Price: {{ cake.cost }}</li>
          </ul>
        </div>
        <div class="card-body">
          <p>{{ cake.description }}</p>
        </div>
        <div class="card-body">
          <a class="btn btn-warning" [routerLink]="['/edit', cake.id]">Edit</a> |
          <button type="button" class="btn btn-danger" (click)="openDeleteModal(cake.id)">
            Delete
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<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 Confirmation</h5>
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="modal"
          aria-label="Close"
        ></button>
      </div>
      <div class="modal-body">Are you sure to delete this item?</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)="confirmDelete()">
          Confirm Delete
        </button>
      </div>
    </div>
  </div>
</div>
  • (Line: 21-23) The 'Delete' button click event registered with 'openDeleteModal()' method.
  • (Line: 30-51) Delete confirmation popup modal HTML.

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:

Comments

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n