Latest Code Tutorials

Angular 13 HttpClient Module: Angular Http GET, POST

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

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

We will use XMLHttpRequest for the Angular application.

Angular HttpClient

Angular HttpClient is a built-in module that helps us to send network requests to any server. Angular HttpClientModule is used to send GET, POST, PUT, PATCH, and DELETE requests. In addition, Angular can consume REST API using the Angular HttpClient module.

The HttpClient in @angular/standard/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 has the RxJS Observable-based API. This means that the multiple calls to the HTTP module will all return the observable that we need to subscribe to one way or another.

Here are some key points to remember: 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 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 12 Project

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

ng new ngcrud

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

Setup Angular HttpClient

Angular HttpClient module is already included when creating a new Angular app. We need to register 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 using 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 {}

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

Setup Angular Service File

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

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

So, if we need to send a POST request to the server, 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 responds 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. As a result, the component becomes harder to understand and test, and the data access logic can’t be re-used or standardized.

That’s why it is best 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 the 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

We have a server running that can feed our data to our React Bootstrap Application.

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

Angular HttpClient GET request.

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

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 an example of a small service that queries the database above using an HTTP GET and fetches the data. This data then goes to the related component and uses HTML, and we can show the data on the screen.

The above example is using the HTTP module in a small service file 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 into the constructor/
  2. Then we call the get() method, which returns the data.

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

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 create two functions for handling and printing errors log.

There are the new required modules, so add them 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 defined local const. So we used the object short-hand creation notation to describe the configuration object.

Angular PUT request

Like in GET requests, 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, we want to update a single property. And this is the primary use case for using the HTTP PATCH method.

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

Angular HttpClient DELETE request

Another frequent operation that we want to do is 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 many other use cases exist.

That’s it for the HttpClient module in Angular.

Recommended Posts

Angular Modal

Angular File Upload

Angular NgClass

Angular Forms

Angular NgFor

1 Comment
  1. Michael says

    Great until you get down to config.service.ts then each section of code is missing what file it should go in. Could you update this to explicitly say where each block of code goes?

Leave A Reply

Your email address will not be published.

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