Skip to main content

Work with Angular HttpClient 13

Step 4 — Setting up Angular HttpClient 13 in our Example Project

Front end applications, built using frameworks like Angular communicate with backend servers through REST APIs (which are based on the HTTP protocol) using either the XMLHttpRequest interface or the fetch() API.

Angular HttpClient makes use of the XMLHttpRequest interface that supports both modern and legacy browsers.

The HttpClient is available from the @angular/common/http package and has a simplified API interface and powerful features such as easy testability, typed request and response objects, request and response interceptors, reactive APIs with RxJS Observables, and streamlined error handling.

Why Angular HttpClient?

The HttpClient builtin service provides many advantages to Angular developers:

  • HttpClient makes it easy to send and process HTTP requests and responses,
  • HttpClient has many builtin features for implementing test units,
  • HttpClient makes use of RxJS Observables for handling asynchronous operations instead of Promises which simplify common web development tasks such as
  • The concelation of HTTP requests,
  • Listening for the progression of file download and file upload operations,
  • Easy error handling,
  • Retrying failed HTTP requests, etc.

Now after introducing HttpClient, let's proceed to building our example application starting with the prerequisites needed to successfully complete our Angular 13 tutorial.

In this step, we'll proceed to set up the HttpClient module in our example.

HttpClient lives in a separate Angular module, so we'll need to import it in our main application module before we can use it.

Open your example project with a code editor or IDE. I'll be using Visual Studio Code.

Next, open the src/app/app.module.ts file, import [HttpClientModule](https://angular.io/api/common/http/HttpClientModule#description) and add it to the imports array of the module as follows:

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

That's all, we are now ready to use the HttpClient service in our project but before that we need to create a couple of components — The home and about components. This is what we'll learn to do in the next step.