Learn Angular 8 Step By Step In 10 Days - HttpClient Or Ajax Call - Day Nine

Welcome back to the Learn Angular 8 in 10 Days article series - Part 9. In the previous article, we discussed the different concepts of Service in Angular. Now, in this article, we will discuss the Concept of AjaxCall. If you want to read the previous articles of this series, then follow the links.
So, in this article, we will discuss how to perform Ajax requests in Angular Framework. Nowadays, when we build any web-based application, we need to call several external HTTP APIs for different types of data related operations. For that purpose, Angular Framework provides its own HTTP client library which can be used to perform these types of operations. In the Javascript environment, the HTTP request is always an asynchronous operation which means it just sends the HTTP request to the API and it executes the next line of code without waiting for the response of the call. And when the API returns the response after some milliseconds or seconds or minutes it notified us and we can start the processing on the based of the response. So, in Angular there are two different ways to handle these types of operations – one is Observables and another is Promises. We will briefly discuss these two later in this article.
 

Basic Idea of Ajax Call

 
Ajax stands for Asynchronous JavaScript and XML. Actually, Ajax is not any programming language or framework or tool. Ajax is basically is a concept to client-side script that communicates between the server and the client machine to perform any type of operations. The best definition as per Ajax in the overview of SPA based application will be “Ajax is a method to exchange or pull data from a server ”. In a basic concept, Ajax always refers to the use of XmlHttpRequest objects to interact with a web server dynamically via JavaScript library. There are several benefits we can achieve by using Ajax in any web-based application like – 
  1. Ajax is used to perform callback operations, which make a perfect quick round trip to and from the server to send or retrieve data without post the entire page to the server. In this way, we can minimize the network utilization and application performance can be a boost.
  2. Ajax always allows us to make asynchronous calls to a web server. In this way, the client browser avoids waiting for all data to arrive before allowing the user to act once more.
  3. Since Ajax call, complete page postback is not required, so any Ajax-enabled web application will always be more responsive and user-friendly.
  4. With the help of Ajax, we can improve the speed, performance, and usability of a web application. 

About HttpClient


In Angular 6, Google first introduced a new easier way to operate with http requests with the new library called HttpClient. Angular provides the new library name so that it can avoid the new breaking changes made with the existing Http library. With the help of this new Http library, we can take advantage of the new functionality like the ability to listen for progress events, interceptors monitor to modify requests or response. Actually, the HTTP module always uses RxJS Observable-based API internally. For this reason, when we pass multiple ajax calls to the server using the HTTP module, it will return all responses as an observable object which we need to subscribe to one way or another. When we working using observable objects we need to remember some key points like,
  • To receive the value as a response against any HTTP calls we need to subscribe to the observables. If we forget to subscribe, then nothing will happen.
  • If we subscribe multiples times to the observables, then multiple HTTP requests will be triggered.
  • By nature or type, every observable are single-value streams. So, if the HTTP request is successful then these observables will emit only one value and then complete.
  • If the HTTP request fails, then these Observables emit an error. 
To use the HttpClient in an Angular application, we need to import the HttpClientModule module into the root module of the application to use the Http Service.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4.   
  5. import { AppComponent } from './app.component';  
  6.   
  7. @NgModule({  
  8.   declarations: [  
  9.     AppComponent  
  10.   ],  
  11.   imports: [  
  12.     BrowserModule,HttpClientModule  
  13.   ],  
  14.   bootstrap: [AppComponent],  
  15.   schemas: [NO_ERRORS_SCHEMA]  
  16. })  
  17. export class AppModule { }  

What are Observables?


Observable is one of the existing features used in the Angular Framework. But basically, it is not the Angular specific features, rather it is a proposed standard for managing any type of async data or operation which will be considered in the ES7 version. With the help of Observables, we can perform the continuous operations for multiple communication through which multiple values of data can be passed. So, by using Observables we can deal with array-like data operations to parse, modify and maintain data. That’s why the Angular framework use observables extensively.

Observables are actually a new primitive type that basically acts as a blueprint for how we want to create streams, subscribe to them, react to new values and combine streams together to build new streams. 
 

What are Promises?


In our application, when we execute any task synchronously, we wait for it to finish before moves to the next line of code. But if we execute the same task asynchronously, the program moves to the next line of code before the task finished its job, maybe finishing off that task may require a few seconds or more. So in a simple word, we can assume that synchronous programming like waiting in line or queue and asynchronously programming like taking a ticket and don’t wait in a queue. Since we have a ticket we can do some other tasks and when that particular task completed it will notify us against that ticket. One of the easiest ways to program asynchronously is to use callbacks functions. We can pass to an asynchronous function a function as a parameter which will be invoked when the task is completed. 
  1. function doAsyncTask(cb) {  
  2.     setTimeout(() => {  
  3.     console.log("Async Task Calling By Callback Function");  
  4.     cb();  
  5.   }, 1000);  
  6. }  
  7.   
  8. doAsyncTask(() => console.log("Callback Function Called"));  
In the above example, doAsyncTask function will be fired an asynchronous task and returns immediately. When the async task completes, a function will be called. It is a callback function, as initialize by short name cb, because of it calls-you-back.

ES6 provides us an alternative mechanism built into the language called a promise. So, the promise is a placeholder for future value. It basically serves the same functionality as callbacks but it provides a nice and organized syntax which provides us an easier way to handle errors. We can create an instance of a promise by called new on the Promise class like below,
  1. var promise = new Promise((resolve, reject) => {  
  2. });  
We always pass an inner function with two arguments (resolve, reject). As we define the function, we can call or named this argument whenever we want, but the standard convention is to call them as resolve and reject. Actually, resolve and reject are in fact functions themselves. Within this inner function, we actually perform our asynchronous processing and then when we are ready we can call the resolve() as below,
  1. var promise = new Promise((resolve, reject) => {  
  2.     setTimeout(() => {  
  3.       console.log("Async Work Complete");  
  4.       resolve();  
  5.   }, 1000);  
  6. });  
So, if we want to use the promise in our callback function example, it will be like this,
  1. let error = true;  
  2. function doAsyncTask() {  
  3.   var promise = new Promise((resolve, reject) => {  
  4.     setTimeout(() => {  
  5.     console.log("Async Work Complete");  
  6.     if (error) {  
  7.       reject();  
  8.     }   
  9.     else   
  10.     {  
  11.       resolve();  
  12.     }  
  13.     }, 1000);  
  14.   });  
  15.   return promise;  
  16. }  

Observables vs Promises


When we use HttpClient for the Ajax calls in Angular Framework, we can use both implementations (i.e. observables or promises) which provides an easy way of API operation for handling requests or receiving a response. But still, there are some key differences that make Observables a superior alternative compared to the promises,
  • Promises can only accept one value at a time unless we compose multiple promises execution plan (Eg: $q.all).
  • Promises can’t be canceled if required.
In Angular 8, it mainly introduces reactive programming concepts totally based on the observables for dealing with the asynchronous processing of data. In earlier versions of Angular (i.e. Angular 1.x), we normally use promises to handle the asynchronous processing related to the ajax call. But still, in Angular 8, we can still use the promises for the same purpose in place of observables. The main objective of reactive programming is the observable element which mainly used to the model or variable which can be observed. Basically, at the normal concept, promises and observables both seem to very similar to each other. Both observables and promises are used to execute asynchronous ajax call along with callback functions for both successful and error responses and also notify or inform us when the result is there.
 

How to Define Observables


So before we start discussing HTTP verbs, first we need to understand how we can define observables objects. So, to create an observable, we need to use the create method of the Observable object. We need to provide a function object as a parameter in which we need to initialize the observable processing. This function can return a function to cancel the observable. 
  1. var observable = Observable.create((observer) => {  
  2.   setTimeout(() => {  
  3.     observer.next('some event');  
  4.   }, 500);  
  5. });  
Just like promises, observables can also provide multiple notifications with the help of different methods as below,
  • next – It emits an event and it can be executed several times.
  • error – It mainly used to throw an error. Once it is executed the stream will be a break. It means error callback will be called immediately and no more events or steps can be executed.
  • complete – It is used to indicate that the observable as completed. After these events, no events will be executed. 
With the help of observables, we can register the callback for previously described notifications. The subscribe method tackles this issue. It can accept three callback function as parameters,
  • onNext – This callback will be called when an event is triggered.
  • onError – This callback will be called when an error is thrown.
  • onCompleted – This callback will be called when an observable complete. 

Http Verbs


In the HTTP protocol, a set of verbs has been described for each type of operation or URL. For any URL, we can perform a GET, PUT, POST, DELETE, HEAD, and OPTIONS request. In this section, we will discuss how to execute the API URL for the mentioned verbs. For that purpose, we assume that we perform the dependency injection for HttpClient in the constructor level of the component as below,
  1. constructor(private http: HttpClient) {  
  2. }  
GET
 
To perform a GET request, we need to simply call the get function on our http client. This will returns an observable which needs to subscribe to receive the data or response from the server-side.
  1. performGET() {  
  2.     console.log("GET");  
  3.     let url = `http://localhost/get`;  
  4.     this.http.get(url).subscribe(res => console.log(res.text()));  
  5. }  
DELETE
 
To Perform a DELETE request we just need to call the delete function of the http client. The format or the function is quite similar to the get function as above. But we can pass query params within this function.
  1. performDELETE() {  
  2.     console.log("DELETE");  
  3.     let url = `http://localhost/delete`;  
  4.     let search = new URLSearchParams();  
  5.     search.set('foo''moo');  
  6.     search.set('limit', 25);  
  7.     this.http.delete(url, {search}).subscribe(res => console.log(res.json()));  
  8. }  
POST
 
To perform a POST request, we call the post function of the http client. The format of the post function is the same as getting a function. But we normally perform the POST request to pass the data as well as to the server. So the in the second parameter in case of post, need to pass an object in place of query parameters which will be passed as the payload for the request. 
  1. performPOST() {  
  2.     console.log("POST");  
  3.     let url = `http://localhost/post`;  
  4.     this.http.post(url, {moo:"foo",goo:"loo"}).subscribe(res =>  
  5.     console.log(res.json()));  
  6. }  
PUT
 
To perform a PUT request we just need to call the put function. It will work exactly the same as the post function. 
  1. performPUT() {  
  2.     console.log("PUT");  
  3.     let url = `http://localhost/put`;  
  4.     let search = new URLSearchParams();  
  5.     search.set('foo''moo');  
  6.     search.set('limit', 25);  
  7.     this.http.put(url, {moo:"foo",goo:"loo"}, {search}).subscribe(res =>  
  8.     console.log(res.json()));  
  9. }  

Handling Errors

 
When we perform an ajax call from our Angular application,an error or exceptions on the server-side may occur. In that case, it will return that error or exception message to the angular application. So we need to know how we can receive that exception message so that we can display those messages in the front of the user or store in our error logs. So, whether we are handling the response as an Observable or as a Promise, we can always implement error handling function as the second param of the http method. In case of a promise, it looks like as below,
  1. performGETAsPromiseError() {  
  2.     console.log("GET AS PROMISE ERROR");  
  3.     let url = `http://localhost/post`;  
  4.     this.http.get(url)  
  5.     .toPromise()  
  6.     .then(  
  7.       res => console.log(res.json()),  
  8.       msg => console.error(`Error: ${msg.status} ${msg.statusText}`) ①  
  9.     );  
  10. }  
In the case of observables, the same will look the below,
  1. performGETAsError() {  
  2.     console.log("GET AS OBSERVABLES ERROR");  
  3.     let url = `http://localhost/post`;  
  4.     this.http.get(url).subscribe(  
  5.       res => console.log(res.json()),  
  6.       msg => console.error(`Error: ${msg.status} ${msg.statusText}`)  
  7.     );  
  8. }  

Headers


In Ajax call, another important part is HTTP headers through which we can pass several configuration-related information to the server-side. By nature, HTTP headers are types of meta-data which normally attached by the browser when we call any HTTP request. Sometimes we need to pass some extra customer headers with our ajax request and we can do that very easily with the help of Angular http client. For this purpose, we first need to import two helper classes from the http module in our component or service. 
  1. import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';  
We first need to create an instance of the HttpHeaders and then we can define our mentioned headers in that instance as below –
  1. const httpOptions = {  
  2.         headers: new HttpHeaders({  
  3.           'Content-Type''application/json; charset=utf-8'  
  4.         })  
  5.       };  
After it, we just need to pass the httpHeader to the proper HTTP verb function.
  1. performPOST() {  
  2.     console.log("POST");  
  3.     let url = `http://localhost/post`;  
  4.     this.http.post(url, {moo:"foo",goo:"loo"},httpOptions).subscribe(res =>  
  5.     console.log(res.json()));  
  6.   }  

Demo 1 - Http Core API Samples


Now in this demo, we will demonstrate how to use ajax call in Angular. For this purpose, we will develop a complete flow related to the employee where we can perform employee add, display existing records, edit data or delete employee data. In this sample demo, we create three different components as below –
  • EmployeeListComponent – For display list employee of information
  • AddEmployeeComponent – For Add New Employee Details
  • UpdateEmployeeComponent – For update existing Employee Details
app.component.employeelist.ts
  1. import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';  
  2. import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';  
  3.   
  4. @Component({  
  5.   selector: 'employee-list',  
  6.   templateUrl: 'app.component.employeelist.html'  
  7. })  
  8.   
  9. export class EmployeeListComponent implements OnInit {  
  10.   
  11.   public data: any = [];  
  12.   public showDetails: boolean = true;  
  13.   public showEmployee: boolean = false;  
  14.   public editEmployee: boolean = false;  
  15.   private _selectedData: any;  
  16.   private _deletedData: any;  
  17.   
  18.   constructor(private http: HttpClient) {  
  19.   }  
  20.   
  21.   ngOnInit(): void {  
  22.   
  23.   }  
  24.   
  25.   ngAfterViewInit(): void {  
  26.     this.loadData();  
  27.   }  
  28.   
  29.   private loadData(): void {  
  30.     let self = this;  
  31.     this.http.get("http://localhost:81/SampleAPI/employee/getemployee")  
  32.       .subscribe((res: Response) => {  
  33.         self.data = res;  
  34.       });  
  35.   }  
  36.   
  37.   private addEmployee(): void {  
  38.     this.showDetails = false;  
  39.     this.showEmployee = true;  
  40.   }  
  41.   
  42.   private onHide(args: boolean): void {  
  43.     this.showDetails = !args;  
  44.     this.showEmployee = args;  
  45.     this.editEmployee = args;  
  46.     this.loadData();  
  47.   }  
  48.   
  49.   private onUpdateData(item: any): void {  
  50.     this._selectedData = item;  
  51.     this._selectedData.DOB = new Date(this._selectedData.DOB);  
  52.     this._selectedData.DOJ = new Date(this._selectedData.DOJ);  
  53.     this.showDetails = false;  
  54.     this.editEmployee = true;  
  55.   }  
  56.   
  57.   private onDeleteData(item: any): void {  
  58.     this._deletedData = item;  
  59.     if (confirm("Do you want to Delete Record Permanently?")) {  
  60.       let self = this;  
  61.       const httpOptions = {  
  62.         headers: new HttpHeaders({  
  63.           'Content-Type''application/json; charset=utf-8'  
  64.         })  
  65.       };  
  66.       this.http.post("http://localhost:81/SampleAPI/employee/DeleteEmployee"this._deletedData, httpOptions)  
  67.           .subscribe((res: Response) => {  
  68.               self.loadData();  
  69.           });  
  70.     }  
  71.   }  
  72. }  
app.component.employeelist.html
  1. <div class="panel">  
  2.   <h3>HTTP Module Sample - Add and Fetch Data</h3>  
  3.   <div class="panel-body container-fluid" *ngIf="showDetails">  
  4.     <div class="row row-lg">  
  5.       <table class="table" style="width:100%;">  
  6.         <thead>  
  7.           <tr>  
  8.             <th class="cell-100">Srl No</th>  
  9.             <th class="cell-300">Alias</th>  
  10.             <th class="cell-300">Employee Name</th>  
  11.             <th class="cell-300">Date of Birth</th>  
  12.             <th class="cell-300">Join Date</th>  
  13.             <th class="cell-300">Department</th>  
  14.             <th class="cell-300">Designation</th>  
  15.             <th class="cell-300">Salary</th>  
  16.             <th class="cell-180"></th>  
  17.           </tr>  
  18.         </thead>  
  19.         <tbody>  
  20.           <tr *ngFor="let item of data">  
  21.             <td class="cell-100">{{item.Id}}</td>  
  22.             <td class="cell-300">{{item.Code}}</td>  
  23.             <td class="cell-300">{{item.Name}}</td>  
  24.             <td class="cell-300">{{item.DOB | date :'shortDate'}}</td>  
  25.             <td class="cell-300">{{item.DOJ | date :'mediumDate'}}</td>  
  26.             <td class="cell-300">{{item.Department}}</td>  
  27.             <td class="cell-300">{{item.Designation}}</td>  
  28.             <td class="cell-300">{{item.Salary |currency:'INR':true}}</td>  
  29.             <td class="cell-180">  
  30.               <a (click)="onUpdateData(item);" style="cursor:pointer;">  
  31.                 <span class="badge badge-primary">Edit</span>  
  32.               </a>      
  33.               <a (click)="onDeleteData(item);" style="cursor:pointer;">  
  34.                 <span class="badge badge-danger">Delete</span>  
  35.               </a>  
  36.             </td>  
  37.           </tr>  
  38.         </tbody>  
  39.       </table>  
  40.       <p>  
  41.         <button class="btn btn-primary" (click)="addEmployee()">  
  42.           Add Employee  
  43.         </button>  
  44.       </p>  
  45.     </div>  
  46.   </div>  
  47.   <div  class="panel-body container-fluid" *ngIf="showEmployee">  
  48.     <employee-add (onHide)="onHide($event);"></employee-add>  
  49.   </div>  
  50.   <div  class="panel-body container-fluid" *ngIf="editEmployee">  
  51.     <employee-update [source]="_selectedData" (onHide)="onHide($event);"></employee-update>  
  52.   </div>  
  53. </div>  
app.component.employeeadd.ts
  1. import { Component, OnInit, EventEmitter, Output } from '@angular/core';  
  2. import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';  
  3.   
  4. @Component({  
  5.   selector: 'employee-add',  
  6.   templateUrl: 'app.component.employeeadd.html'  
  7. })  
  8.   
  9. export class AddEmployeeComponent implements OnInit {  
  10.   
  11.   public _model: any = {};  
  12.   @Output() private onHide: EventEmitter<boolean> = new EventEmitter<boolean>();  
  13.   
  14.   constructor(private http: HttpClient) {  
  15.   }  
  16.   
  17.   ngOnInit(): void {  
  18.   
  19.   }  
  20.   
  21.   public onCancel(): void {  
  22.     this._model = {};  
  23.     this.onHide.emit(false);  
  24.   }  
  25.   
  26.   public submit(): void {  
  27.     if (this.validate()) {  
  28.       let self = this;  
  29.       const httpOptions = {  
  30.         headers: new HttpHeaders({  
  31.           'Content-Type''application/json; charset=utf-8'  
  32.         })  
  33.       };  
  34.       this.http.post("http://localhost:81/SampleAPI/employee/AddEmployee"this._model, httpOptions)  
  35.         .subscribe((res: Response) => {  
  36.           self.onCancel();  
  37.         });  
  38.   
  39.     }  
  40.   }  
  41.   
  42.   private reset(): void {  
  43.     this._model = {};  
  44.   }  
  45.   
  46.   private validate(): boolean {  
  47.     let status: boolean = true;  
  48.     if (typeof (this._model.code) === "undefined") {  
  49.       alert('Alias is Blank');  
  50.       status = false;  
  51.       return;  
  52.     }  
  53.     else if (typeof (this._model.name) === "undefined") {  
  54.       alert('Name is Blank');  
  55.       status = false;  
  56.       return;  
  57.     }  
  58.     else if (typeof (this._model.dob) === "undefined") {  
  59.       alert('dob is Blank');  
  60.       status = false;  
  61.       return;  
  62.     }  
  63.     else if (typeof (this._model.doj) === "undefined") {  
  64.       alert('DOJ is Blank');  
  65.       status = false;  
  66.       return;  
  67.     }  
  68.     else if (typeof (this._model.department) === "undefined") {  
  69.       alert('Department is Blank');  
  70.       status = false;  
  71.       return;  
  72.     }  
  73.     else if (typeof (this._model.designation) === "undefined") {  
  74.       alert('Designation is Blank');  
  75.       status = false;  
  76.       return;  
  77.     }  
  78.     else if (typeof (this._model.salary) === "undefined") {  
  79.       alert('Salary is Blank');  
  80.       status = false;  
  81.       return;  
  82.     }  
  83.     return status;  
  84.   }  
  85. }  
app.component.employeeadd.html
  1. <div class="row row-lg">  
  2.   <h4>Provide Employee Details</h4>  
  3.   <table class="table">  
  4.     <tr>  
  5.       <td>Employee Code</td>  
  6.       <td><input type="text" [(ngModel)]="_model.code" /></td>  
  7.     </tr>  
  8.     <tr>  
  9.       <td>Employee Name</td>  
  10.       <td><input type="text" [(ngModel)]="_model.name" /></td>  
  11.     </tr>  
  12.     <tr>  
  13.       <td>Date of Birth</td>  
  14.       <td><input type="date" [(ngModel)]="_model.dob" /></td>  
  15.     </tr>  
  16.     <tr>  
  17.       <td>Date of Join</td>  
  18.       <td><input type="date" [(ngModel)]="_model.doj" /></td>  
  19.     </tr>  
  20.     <tr>  
  21.       <td>Department</td>  
  22.       <td><input type="text" [(ngModel)]="_model.department" /></td>  
  23.     </tr>  
  24.     <tr>  
  25.       <td>Designation</td>  
  26.       <td><input type="text" [(ngModel)]="_model.designation" /></td>  
  27.     </tr>  
  28.     <tr>  
  29.       <td>Salary</td>  
  30.       <td><input type="number" [(ngModel)]="_model.salary" /></td>  
  31.     </tr>  
  32.     <tr>  
  33.       <td></td>  
  34.       <td>  
  35.         <input type="button" value="Submit" (click)="submit()" />  
  36.              
  37.         <input type="button" value="Cancel" (click)="onCancel()" />  
  38.       </td>  
  39.     </tr>  
  40.   </table>  
  41. </div>  
app.component.employeeupdate.ts
  1. import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';  
  2. import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';  
  3.   
  4. @Component({  
  5.   selector: 'employee-update',  
  6.   templateUrl: 'app.component.employeeupdate.html'  
  7. })  
  8.   
  9. export class UpdateEmployeeComponent implements OnInit {  
  10.   
  11.   public _model: any = {};  
  12.   
  13.   @Input()  
  14.   set source(data: any) {  
  15.     this._model = data;  
  16.   }  
  17.   get source() {  
  18.     return this._model;  
  19.   }  
  20.   
  21.   @Output() private onHide: EventEmitter<boolean> = new EventEmitter<boolean>();  
  22.   
  23.   constructor(private http: HttpClient) {  
  24.   }  
  25.   
  26.   ngOnInit(): void {  
  27.     if (this._model == undefined) {  
  28.       this._model = this.source;  
  29.     }  
  30.   }  
  31.   
  32.   public onCancel(): void {  
  33.     this._model = {};  
  34.     this.onHide.emit(false);  
  35.   }  
  36.   
  37.   public onUpdate(): void {  
  38.     if (this.validate()) {  
  39.       let self = this;  
  40.       const httpOptions = {  
  41.         headers: new HttpHeaders({  
  42.           'Content-Type''application/json; charset=utf-8'  
  43.         })  
  44.       };  
  45.       this.http.put("http://localhost:81/SampleAPI/employee/UpdateEmployee"this._model, httpOptions)  
  46.         .subscribe((res: Response) => {  
  47.           self.onCancel();  
  48.         });  
  49.   
  50.     }  
  51.   }  
  52.   
  53.   private reset(): void {  
  54.     this._model = {};  
  55.   }  
  56.   
  57.   private validate(): boolean {  
  58.     let status: boolean = true;  
  59.     if (typeof (this._model.Code) === "undefined") {  
  60.       alert('Alias is Blank');  
  61.       status = false;  
  62.       return;  
  63.     }  
  64.     else if (typeof (this._model.Name) === "undefined") {  
  65.       alert('Name is Blank');  
  66.       status = false;  
  67.       return;  
  68.     }  
  69.     else if (typeof (this._model.Department) === "undefined") {  
  70.       alert('Department is Blank');  
  71.       status = false;  
  72.       return;  
  73.     }  
  74.     else if (typeof (this._model.Designation) === "undefined") {  
  75.       alert('Designation is Blank');  
  76.       status = false;  
  77.       return;  
  78.     }  
  79.     else if (typeof (this._model.Salary) === "undefined") {  
  80.       alert('Salary is Blank');  
  81.       status = false;  
  82.       return;  
  83.     }  
  84.     return status;  
  85.   }  
  86.   
  87.   private parseDate(dateString: string): Date {  
  88.     if (dateString) {  
  89.       return new Date(dateString);  
  90.     } else {  
  91.       return null;  
  92.     }  
  93.   }  
  94. }  
app.component.employeeupdate.html
  1. <div class="row row-lg">  
  2.   <h4>Provide Employee Details</h4>  
  3.   <table class="table">  
  4.     <tr>  
  5.       <td>Employee Code</td>  
  6.       <td><input type="text" [(ngModel)]="_model.Code" /></td>  
  7.     </tr>  
  8.     <tr>  
  9.       <td>Employee Name</td>  
  10.       <td><input type="text" [(ngModel)]="_model.Name" /></td>  
  11.     </tr>  
  12.     <tr>  
  13.       <td>Date of Birth</td>  
  14.       <td><input type="text" [(ngModel)]="_model.DOB" readonly /></td>  
  15.     </tr>  
  16.     <tr>  
  17.       <td>Date of Join</td>  
  18.       <td><input type="text" [(ngModel)]="_model.DOJ" readonly /></td>  
  19.     </tr>  
  20.     <tr>  
  21.       <td>Department</td>  
  22.       <td><input type="text" [(ngModel)]="_model.Department" /></td>  
  23.     </tr>  
  24.     <tr>  
  25.       <td>Designation</td>  
  26.       <td><input type="text" [(ngModel)]="_model.Designation" /></td>  
  27.     </tr>  
  28.     <tr>  
  29.       <td>Salary</td>  
  30.       <td><input type="number" [(ngModel)]="_model.Salary" /></td>  
  31.     </tr>  
  32.     <tr>  
  33.       <td></td>  
  34.       <td>  
  35.         <input type="button" value="Update" (click)="onUpdate()" />  
  36.              
  37.         <input type="button" value="Cancel" (click)="onCancel()" />  
  38.       </td>  
  39.     </tr>  
  40.   </table>  
  41. </div>  
app.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls : ['./custom.css']  
  7. })  
  8. export class AppComponent implements OnInit {  
  9.     
  10.   ngOnInit(){     
  11.   }  
  12. }  
app.component.html
  1. <div style="padding-left: 20px;padding-top: 20px; width: 1000px;">    
  2.     <div class="row">  
  3.         <div class="col-xs-12">              
  4.             <employee-list></employee-list>  
  5.         </div>  
  6.     </div>  
  7. </div>  
app.module.ts
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  3. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  4. import { HttpClientModule } from '@angular/common/http';  
  5.   
  6. import { AppComponent } from './app.component';  
  7. import { EmployeeListComponent } from './app.component.employeelist';  
  8. import { AddEmployeeComponent } from './app.component.employeeadd';  
  9. import { UpdateEmployeeComponent  } from './app.component.employeeupdate';  
  10.   
  11. @NgModule({  
  12.   declarations: [  
  13.     AppComponent,EmployeeListComponent,AddEmployeeComponent, UpdateEmployeeComponent  
  14.   ],  
  15.   imports: [  
  16.     BrowserModule,HttpClientModule, FormsModule, ReactiveFormsModule  
  17.   ],  
  18.   bootstrap: [AppComponent],  
  19.   schemas: [NO_ERRORS_SCHEMA]  
  20. })  
  21. export class AppModule { }   
Now run the demo in the browser,
 
Employee List  
 
HttpClient Or Ajax Call
New Employee Add
 
HttpClient Or Ajax Call
 
Update Employee Info
 
HttpClient Or Ajax Call 

Conclusion

 
In this article, we discussed how to operate an Ajax call using Angular Framework. Also, we discussed the basic concept of Ajax call along with HttpClient, Observables, and Promises. Now, in the next article, we will discuss how to handle routing in the Angular 8 Framework. I hope, this article will help you. Any feedback or query related to this article is most welcome.