Tanveer Ahmad

Introducing Angular 9/10 HttpClient Module

By Tanveer Ahmad

Last updated cal_iconDecember 16, 2021

The newer HttpClient module is an improved version of the HTTP client API within the @angular/common/HTTP package.

Setting up the HttpClient Module in Angular 9/10

Start by importing the HttpClientModule module from the @angular/common/http package:

import { HttpClientModule } from ‘@angular/common/http’;

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

After adding the module to the imports array, we can now use the new HttpClient API to send GET, POST, PUT and DELETE requests to a REST HTTP server.

Creating an Example Dummy API Server for Our Angular Application

In simple words: API may be a set of HTTP endpoints that provide a CRUD (Create, Read, Update, and Delete) interface on some server resources.

Creating the API

First, you would like to put in JSON-server via npm by running the subsequent command:

  • npm install -g JSON-server

Next, you would like to make a JSON file, which can act as a database for our server. First, create a folder for our project and navigate inside it.

$ mkdir angular-project-demo

  • $ cd angular-project-demo

Next, create a server folder inside the project-demo folder and navigate to it:

  • $ mkdir server
  • $ cd server

Next, create a database.json file.

  • $ touch database.json

Open the server/database.json file and add the subsequent data.

“student”: [
{
“name”: “Abc”,
“address”: “xyz”,
“phone”: “00000099999”,
“email”: “[email protected]”,
“password”: “123456”,
“id”: 1
},

First, initialize an empty Node.js module in the server folder.

  • $ npm init -y

This will generate a package.json file with default values. Finally, run the API server by executing the following command.

json-server –watch database.json

These are the API endpoints we’ll be ready to use via this REST server and using the previous configuration:

  • GET /customers for getting the purchasers,
  • GET /customers/ for getting one customer by id,
  • POST /customers for creating a replacement customer,
  • PUT /customers/ for updating a customer by id,
  • PATCH /customers/ for partially updating a customer by id,
  • DELETE /customers/ for deleting a customer by id.

You can use _page and _limit parameters to urge paginated data. You will get first, prev, next, and last within the Link header.

Installing Angular CLI

$ npm install @angular/[email protected] –global

Creating an Angular Project

$ ng new my-app

Creating an Angular Project

$ ng new my-app

After creating the API server, we will now do our Angular project using Angular CLI. In your terminal, navigate to the project-demo folder and run the subsequent command:

Creating an Angular Service

Let’s start with the HttpService. In your terminal, run:

  • $ cd frontend
  • $ ng g s http

The command will generate the src/app/http.service.ts files.

Creating Angular 10 Components

  • $ ng g c student-list
  • $ ng g c student-details
  • $ ng g c student-create
  • $ ng g c student-update

Adding Routing & Navigation

import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;
import { StudentListComponent } from ‘./Student-list/Student-list.component’;
import { StudentDetailsComponent } from ‘./Student-details/Student-details.component’;
import { StudentCreateComponent } from ‘./Student-create/Student-create.component’;
import { StudentUpdateComponent } from ‘./Student-update/Student-update.component’;
const routes: Routes = [
{ path: ”, pathMatch: ‘full’, redirectTo: ‘list’},
{ path: ‘list’, component: StudentListComponent},
{ path: ‘details/:id’, component: StudentDetailsComponent},
{ path: ‘create’, component: StudentCreateComponent},
{ path: ‘update’, component: StudentUpdateComponent},
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

HTTP GET Requests using HttpClient in Angular

  • Import HttpClient from @angular/common/http.
  • Inject HttpClient via component constructor.
  • Make HTTP GET Requests using .get(endpoint) method.
  • Subscribe to the returned observable and show results.

Sending HTTP PUT Requests in Angular 

The HTTP PUT method is employed to completely replace a resource on the API server. we will use the HttpClient module to send a PUT request to an API server using the put () method. For example:

this.httpClient.patch(“http://localhost:3000/student/1”),
{
“name”: “Newstudent01”,
“email”: “[email protected]”,
“tel”: “1234567”
})
.subscribe(
data => {
console.log(“PUT Request is successful “, data);
},
error => {
console.log(“Rrror”, error);
}
);

Sending HTTP PATCH Requests

The HTTP PATCH method is employed to update a resource on the server. The HttpClient class provides the patch() method that is often wont to send UPDATE requests. For example: 

this.httpClient.patch(“http://localhost:3000/student/1”),
{
“email”: “[email protected]
}).subscribe(
data => {
console.log(“PUT Request is successful “, data);
},
error => {
console.log(“Error”, error);
}
);

Sending HTTP DELETE Requests

Now let’s examine an example of how we will send an HTTP DELETE request to delete a resource from the API server using delete () method provided by the HttpClient class:

this.httpClient.patch(“http://localhost:3000/student/1”),
.subscribe(
data => {
console.log(“PATCH Request is successful “, data);
},
error => {
console.log(“Error”, error);
}
);

Sending HTTP POST Requests 

The HTTP POST method has many uses but mostly used once we got to add new data on the server so let’s take an example of adding a replacement customer to our API server database using the post() method of the HttpClient class:

this.httpClient.patch(“http://localhost:3000/student/1”),
.subscribe(
data => {
console.log(“PATCH Request is successful “, data);
},
error => {
console.log(“Error”, error);
}
);

We are calling the post () method from the injected instance of HTTP Client. The primary parameter is the API endpoint, and therefore, the second parameter is the student data object. We also subscribe to the observable returned by the post () method.  If the operation is successful, we display POST Request and the data on the console. If there’s a mistake, we log the error on the console.

Conclusion

So, we’ve seen how to interact with an API server using standard HTTP methods i.e., PUT, PATCH, DELETE and POST in Angular. For the sake of testing, we’ve used a Dummy API server, but you’ll use an equivalent example with an accurate backend server.

Get In Touch

How Can We Help ?

We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market

We specialize in full-stack software & web app development with a key focus on JavaScript, Kubernetes and Microservices
Your path to drive 360° value starts from here
Enhance your market & geographic reach by partnering with NodeXperts