Tanveer Ahmad

Frontend Developer Software Developer || Fascinated by tech trends || Building usable systems that work on web and mobile.

Introducing Angular 9/10 HttpClient Module

The newer HttpClient module which is an improved version of the Http client API that lives 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 are now able to 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. within the Link header you will get first, prev, next and last links.

Installing Angular CLI

$ npm install @angular/cli@next --global

Creating an Angular Project

$ ng new myapp

Creating an Angular Project

$ ng new myapp

After creating the API server, we will now proceed to make 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"),

{
"name":  "student02",
"email":  "[email protected]",
"tel":  "1234567"
})
.subscribe(
data  => {
console.log("POST Request is successful ", data);
},
error  => {

console.log("Error", error);

}

);

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

Conclusion

So we’ve seen the way to interact with an API server using common 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 a true backend server.

Share