Menu Close

How to use HttpClient in Angular

In this article we will learn about How to use HttpClient in Angular. HttpClient is an injectable service, it comes with the various powerful methods to communicate with the remote server. HttpClient API can send Http POST, GET, PUT and DELETE requests easily. Please read my previous article about Dependency Injection in Angular and Angular Services.

What is the use of HttpClient?

HttpClient is a built-in service class available in the @angular/common/http package. It has multiple signature and return types for each request. It uses the RxJS observable-based APIs, which means it returns the observable and what we need to subscribe it. This API was developed based on XMLHttpRequest interface exposed by browsers.

Why we need HttpClient?

The front-end of applications communicate with back-end services to get or send the data over HTTP protocol using either XMLHttpRequest interface or fetch API. This communication is done in Angular with the help of HttpClient.

Features of HttpClient

  • Provides typed request and response objects
  • Contains testability features
  • Intercepts request and response
  • Supports RxJS observable-based APIs
  • Supports streamlined error handling
  • Performs the GET, POST, PUT, DELETE operations

How to use HttpClient in Angular

The HttpClient is a separate model in Angular and is available under the @angular/common/http package. The following steps show you how to use the HttpClient in an Angular app.

Import HttpClient Module in Root Module

We need to import the HttpClient inside the app.module in root modules.

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Leave a Reply

Your email address will not be published.