Angular Http

HttpClient

Angular is a complete platform for creating client side applications so, we don't need any other external libraries for doing common operations like Http requests. Angular provides the HttpClientModule, which allows us to send Http requests and make API calls to remote Http servers. HttpClient is available from the package @angular/common/http.

Modern web browsers has two standard APIs for sending Http requests i.e. XMLHttpRequest interface and the fetch(). The HttpClientModule is built on top of the XMLHttpRequest interface. HttpClientModule wraps all the complexities of XMLHttpRequest interface and provides extra features such as:-

Testability features.

Testability features. Types for requests and responses.

Types for requests and responses. Request and response interception.

Request and response interception. Observable based APIs.

Observable based APIs. Better error handling.

HttpClient Configuration

To establish communication between front-end and back-end we can use HttpClient, and to use this module just follow the below steps:-

Step 1

To use HttpClient, first we neet to import it from @angular/common/http in the main root module.

example import { HttpClientModule } from '@angular/common/http';

Step 2

Now, add HttpClientModule module to the imports array of the main root module.

example import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ ], imports: [ BrowserModule, HttpClientModule ], providers: [ ], bootstrap: [ AppComponent ] }) export class AppModule { }

Step 3

Now, having imported HttpClientModule into the main root module, you can inject the HttpClient into any where in the application class.

example import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class AppService { constructor(private http: HttpClient) { } }

Example for Calling a RESTful API through HttpClient

Calling a GET request

Calling a POST request

Calling a PUT request

Calling a PATCH request

Calling a DELETE request

Http Request and Response Interception

Http Interception is a one of the major feature of @angular/common/http package introduced in Angular version 4.3. With interception, we can declare interceptors that inspect and transform HTTP requests/responses between our application and the server.

To implement a Http Interceptor, first we have to declare a class that implements the intercept() method of the HttpInterceptor interface.