HttpClient Service

In this lesson, we will briefly look at the use of HttpClient module in Angular to perform HTTP operations.

intro-httpclient

Angular provides a simplistic HTTP API for performing HTTP operations in angular applications. The front-end applications need to communicate with a server over the HTTP protocol to download data, upload data, and access other back-end services.

Features of HTTP

It offers features like:

  • Error handling
  • Request and response interception.
  • Typed response objects

Working with HTTP

To work with the HTTP protocol in Angular, we need to have the required imports from the HTTP packages.

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

Add it to the imports array:

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule
  ],

We can then inject the HttpClient service in the application service required to fetch the data:

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

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

Definition of HttpClient

Look at the definition of the HttpClient service here:

export declare class HttpClient {
    private handler;
    constructor(handler: HttpHandler);
    /**
     * Sends an `HTTPRequest` and returns a stream of `HTTPEvents`.
     *
     * @return An `Observable` of the response, with the response body as a stream of `HTTPEvents`.
     */
    request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>;
    /**
     * Constructs a request that interprets the body as an `ArrayBuffer` and returns the response in an
     * `ArrayBuffer`.
     *
     * @param method  The HTTP method.
     * @param url     The endpoint URL.
     * @param options The HTTP options to send with the request.
     *
     *
     * @return An `Observable` of the response, with the response body as an `ArrayBuffer`.
     */
    request(method: string, url: string, options: {
        body?: any;
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'arraybuffer';
        withCredentials?: boolean;
    }): Observable<ArrayBuffer>;
    /**
     * Constructs a request that interprets the body as a blob and returns
     * the response as a blob.
     *
     * @param method  The HTTP method.
     * @param url     The endpoint URL.
     * @param options The HTTP options to send with the request.
     *
     * @return An `Observable` of the response, with the response body of type `Blob`.
     */
    request(method: string, url: string, options: {
        body?: any;
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'blob';
        withCredentials?: boolean;
    }): Observable<Blob>;
    /**

Using HttpClient methods

We can use the provided request method from the API to perform all the different operations by providing methods like GET, POST, PUT, and DELETE.

For example,

  public request(requestOption): Observable<any> {
    return this._httpClient.request(
      requestOption.method,
      requestOption.url,
      {
        headers: this._getHttpHeaders(requestOption.headerConfig),
        params: requestOption.params,
        body: requestOption.body,
        observe: 'response',
        responseType: requestOption.responseType ? requestOption.responseType : 'json'
      })
      .pipe(
        map(data => this._extractData(data)),
        catchError(data => this._handleError(data))
      );
  }

The get method of the API accepts two parameters. The URL, and the options wherein you can specify the headers, params etc.:

options: {
    headers?: HttpHeaders | {[header: string]: string | string[]},
    observe?: 'body' | 'events' | 'response',
    params?: HttpParams|{[param: string]: string | string[]},
    reportProgress?: boolean,
    responseType?: 'arraybuffer'|'blob'|'json'|'text',
    withCredentials?: boolean,
  }

Get hands-on with 1200+ tech skills courses.