Latest Code Tutorials

Angular HttpClient Module | Angular Http GET, POST Example


Angular 9 HttpClient is an inbuilt module that helps us to send network requests to any server. Angular HttpClientModule is used to send GET, POST, PUT, PATCH, and DELETE requests. Angular can consume REST API using the Angular HttpClient module. The latest version of the Angular framework is Angular 9.

If you are new to Angular 9, then check out my Angular 9 Tutorial in this blog. Most front-end applications communicate with the backend services over an HTTP protocol. Modern browsers support the two different APIs for making HTTP requests.

  1. XMLHttpRequest interface and the 
  2. fetch() API.

We will use XMLHttpRequest for Angular application.

Angular 9 HttpClient Example

The HttpClient in @angular/common/Http offers the simplified client HTTP API for Angular applications that rests on an XMLHttpRequest interface exposed by browsers.

Additional benefits of the HttpClient include testability features, typed request and response objects, request and response interception, Observable APIs, and streamlined error handling.

Angular HTTP module

The Angular HTTP module all have the RxJS Observable-based API. What this means is that the multiple calls to the HTTP module will all return the observable, that we need to subscribe to one way or the other way.

Here are some key points to bear in mind that a particular type of Observables returned by an HTTP module.

  1. If we don’t subscribe to the observables, nothing will happen.
  2. If we subscribe to the multiple times to these observables, multiple HTTP requests will be triggered (see this post for more details).
  3. This particular type of Observables are the single-value streams: If an HTTP request is successful, these observables will emit only one value and then complete.
  4. These observables will emit the error if the HTTP request fails, more on this later.

Setup Angular 9 Project

We have already set up an Angular CLI, and now we need to create a project using the following command.

ng new ng8crud

It will create a new project and install the required files to set up the boilerplate.

Setup Angular HttpClient

Angular 9 HttpClient module already included when creating a new Angular app. We just need to register it this Angular app. Open and edit `src/app/app.module.ts` then add this import of HttpClientModule that is part of @angular/common/http.

Before you can use a HttpClient, you need to import an Angular HttpClientModule. Most apps do import in the root AppModule.

// app.module.ts

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

  imports: [
    // import HttpClientModule after BrowserModule.
  declarations: [
  bootstrap: [ AppComponent ]
export class AppModule {}

Now, the Angular HttpClient is ready to use or inject with the Angular service or component.

Setup Angular Service File

In Angular application, it is a best practice to create a service file related to a particular angular module.

If an angular app needs to interact with the back end server, then we can write the API calling code inside the service file.

So, if we need to send a POST request to the server, then we import the HttpClient inside the service file and make an AJAX request to the server with the data object. After a successful request, the server sends a response back to the client.

You typically post-process the data, add the error handling logic, and maybe some retry logic to cope with intermittent connectivity.

The component quickly becomes cluttered with the data access. The component becomes harder to understand, even harder to test, and the data access logic can’t be re-used or standardized.

That’s why it is the best practice to separate the presentation of the data from data access by encapsulating the data access in the separate service and delegating to that service in a component.

So, now create a service file by the following command.

ng g s config

Now, write the following code inside the config.service.ts file.

// config.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class ConfigService {
  constructor(private http: HttpClient) { }

Create a backend Server

We need the fake data to work with and that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using the Yarn package manager.

yarn global add json-server

# or

npm install -g json-server

Now we need to create the folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside the db.json file.

    "characters": [
        "id": "1",
        "name": "Peter Dinklage",
        "age": "45"
        "id": "2",
        "name": "Lina Heady",
        "age": "43"
        "id": "3",
        "name": "Emilia Clarke",
        "age": "30"
        "id": "4",
        "name": "Kit Harrington",
        "age": "30"
        "id": "5",
        "name": "Sean Bean",
        "age": "50"

Now, start the JSON server using the following command.

json-server --watch src/data/db.json --port 4000

Now, we have the server running that can feed our data to our React Bootstrap Application.

Our JSON server is started at port: 4000 and URL is http://localhost:4000/characters.

Angular HttpClient GET request

We have created a backend server and also created a service file.

Now, we need to write the code that sends a GET request to the json server.

So, write the following code inside the config.service.ts file.

// config.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class ConfigService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getCharacters() {
    return this

And here is the example of a small service that queries the database above using an HTTP GET, and fetch the data. This data then goes to the related component and using HTML, and we can show the data on the screen.

The above example is using the HTTP module in a small service file, that is displaying a list of characters. Let’s break down the following example step-by-step:

  1. We are using the new HttpClient client module, and injecting it in the constructor/
  2. Then we are calling the get() method, which is returning the data.

The HttpClient.get() method parsed a JSON server response into an anonymous Object type. It doesn’t know what shape or attributes of that object is.

You can tell the HttpClient the type of response to make consuming the output easier and more prominent.

First, define the interface with the Characters attribute.

export interface Characters {
    id: Number;
    name: String;
    age: Number;

Then, specify that interface as an HttpClient.get() call’s type parameter in the service.

Angular HttpClient Error Handling

We have to add an error handling to handle any error on every HttpClient request. Write the following code inside the config.service.ts file.

private handleError(operation = 'operation', result?: T) {
  return (error: any): Observable => {
    this.log(`${operation} failed: ${error.message}`);

    return of(result as T);

private log(message: string) {

In the above codes, we are creating two functions for handle error and print log of error.

There are the new required modules, so, add it to existing imports.

import { Observable, of } from 'rxjs';

Next, add a HttpClient request function with catchError.

getCharacters() {
    return this.http.get(`${this.url}/characters`).pipe(
      catchError(this.handleError<Characters[]>('characters', [])));

Angular HTTP Headers

If we want to add the custom HTTP Headers in our HTTP request then, in addition to the headers the browser already attaches automatically. We can do this by using the HttpHeaders class.

const headers = new HttpHeaders()
            .set("X-CustomHeader", "custom header value");

getCharacters() { 
   return this 
          .get(`${this.url}/characters`, {headers}); }

As we can see, HttpHeaders also has an immutable API, and we are passing a configuration object as the second argument of the get() call.

This configuration object only has one property named headers, just like the local const that we defined – so we used the object short-hand creation notation to describe the configuration object.

Angular PUT request

Just like in the case of GET request, we can also use the Angular HTTP Client to do all the other available HTTP methods, namely the methods typically used for data modification such as PUT.

The PUT method should only be used if we want to replace the value of the resource.

Angular PATCH request

Most often than not, instead of providing the complete new version of the resource, what we want to do is to update a single property. And this is the primary use case for the use of the HTTP PATCH method.

The PATCH request is useful in situations where there is some further server-side modification of the patched values, such for example via a database trigger or a Firebase rule.

Angular HttpClient DELETE request

Another frequent operation that we want to do is to trigger the logical delete of some data. This operation can completely wipe the data from our database or mark some data as deleted.

Angular HttpClient POST request in Angular

If the operation that we are trying to do does not fit the description of any of the methods above (GET, PUT, PATCH, DELETE), then we can use an HTTP wildcard modification operation: POST.

That operation is typically used to add the new data to the database, although there are many other use cases.

Finally, Angular HttpClient Module Example is over.

Recommended Posts

Angular Modal

Angular File Upload

Angular NgClass

Angular Forms

Angular NgFor

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.