Explore Important Features Of HTTP Client With RxJs Operators

I know at first this will sound like an old topic but believe me you will definitely find some new features within this article.

What to expect from the article?

  • Starting from scratch calling Web API (making GET request)
  • Displaying full results with Headers, Code, Status, Status Text, etc.
  • Dealing with errors (Server-side Errors and Client-side Errors)
  • Some RxJS operators (like retry, catch errors, map etc.)
  • Search using debouncing

So, let’s dive into HTTP Client from scratch.

First, in order to use HTTP Client in an Angular application, we need to import it in the app.module.ts file, as shown below.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4. import { AppComponent } from './app.component';  
  5. @NgModule({  
  6.   declarations: [  
  7.     AppComponent  
  8.   ],  
  9.   imports: [  
  10.     BrowserModule,  
  11.     HttpClientModule  
  12.   ],  
  13.   providers: [],  
  14.   bootstrap: [AppComponent]  
  15. })  
  16. export class AppModule { }  

Generate Service and provide it in root

So, as a first step in fetching the data from our Web API, we will create a service. And as you all might know, services are DRY!! (Don’t Repeat Yourself).

Use the following command for generating services using Angular CLI.

ng g s task

Then, in order to use a service in our application, we first need to provide the services. In general cases, we will be providing our service in our root. From Angular version 6.x and above, we don’t need to provide our services manually to app.module.ts. Instead, we will be following the decorator in our newly created service.

  1. @Injectable({  
  2.   providedIn: 'root'  
  3. })  

So, we can inject the service anywhere in our application.

Introduction to Web API

Now, before making a call to my Web API, I would like to give a brief introduction of the Web API and what it will return.

URL - https://rkdemotask.herokuapp.com/tasks/

GET: Fetch all tasks and return Id, Title, and Status

Below is the sample data.

Note
This Web API is publically available, so there may be chances of garbage data or no data, but if there is data, it will look like the following.

Explore Important Features Of HTTP Client With RxJs Operators 

Generate Task Class 

  1. export class Task {  
  2. public constructor(  
  3. public Id:string,  
  4. public Title:string,  
  5. public Status:string){  
  6.   }  
  7. }  

We have created a class to provide the data structure and to store the data which is returned by the Web API.

Note
Remember to give the same name to the properties to avoid any error in displaying the data on the component.

Creating Method In Service

  1. import { Task } from './task';  
  2. import { Injectable } from '@angular/core';  
  3. import { HttpClient } from '@angular/common/http';  
  4.   
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class TaskService {  
  9. url:string='https://rkdemotask.herokuapp.com/tasks/';  
  10.   constructor(public _http:HttpClient) { }  
  11.   getAllTask(){  
  12.     return this._http.get<Task>(this.url);  
  13.   }  
  14. getAllTaskWithFullResponse(){  
  15.     return this._http.get(this.url,{observe:'response'});  
  16.   }  
  17. }  

First, I have created the instance _http of HttpClient in the constructor.

Then, we are having one method named getAllTasks which will simply make HTTP calls to my Web API and also return all the tasks.

The second method, getAllTaskWithFullResponse, is almost the same method but it will return the full response, i.e., it will return us the response with headers, code, Status Text, Body etc. whereas getAllTask will only return us the data. We can make the full response true by simply passing an observe flag with the response.

Let me show you the result as a snapshot but before that, let me first inject the service on our component and call both the methods.

Injecting Service to app.component.ts

  1. import { TaskService } from './task.service';  
  2. import { Component,OnInit } from '@angular/core';  
  3. import { Task } from './task';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css']  
  9. })  
  10. export class AppComponent implements OnInit {  
  11.   title = 'httpclientDemo';  
  12.   constructor(private _taskdata:TaskService){}  
  13.   ngOnInit(){  
  14.     this._taskdata.getAllTask().subscribe(  
  15.       (data)=>{  
  16.         console.log(“only data” +data);  
  17.       }  
  18.     );  
  19.     this._taskdata.getAllTaskWithFullResponse().subscribe(  
  20.       (data:any)=>{  
  21.         console.log(“full response”+data);  
  22.       }  
  23.     );  
  24.   }  
  25. }  

Note
Always use "Subscribe" because the httpClient method will not begin its HTTP request call until you subscribe() with the method.

Full Response with headers,body,status text and etc. (getAllTaskWithFullResponse)

Explore Important Features Of HTTP Client With RxJs Operators 

Only data (getAllTask)

Explore Important Features Of HTTP Client With RxJs Operators 

Until now, it is just a simple HTTP Call with GET request; nothing special in it, right?

Error Handling

So now, let’s dive a little bit deeper with HTTP Client and handle HTTP Errors. Basically, there are two types of errors when you are making an HTTP call.

  1. Error from server; i.e., server might reject the request with status code 404 or 500. These are due to incorrect addresses or due to internal server errors.
  2. Client-Side Error, i.e., network error which in turn, does not allow making a call or some error because of RxJS operators.

Both of these errors can be handled by HttpClient under HttpErrorResponse. So now, we will create a method which will deal with the error handling and also print the appropriate message to the user.

Modify the task.service.ts file as shown below.

  1. import { Task } from './task';  
  2. import { Injectable } from '@angular/core';  
  3. import { HttpClient, HttpErrorResponse } from '@angular/common/http';  
  4. import { throwError, Observable } from 'rxjs';  
  5. import { catchError } from 'rxjs/operators';  
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class TaskService {  
  10. url:string='https://rkdemotask.herokuapp.com/tasks/';  
  11.   constructor(public _http:HttpClient) { }  
  12.   getAllTaskWithFullResponse(){  
  13.     return this._http.get(this.url,{observe:'response'}).pipe(  
  14.       catchError(this.handleError)  
  15.     );  
  16.   }  
  17.   getAllTask(){  
  18.     return this._http.get<Task>(this.url);  
  19.   }  
  20.   private handleError(ex:HttpErrorResponse){  
  21.     if(ex.error instanceof ErrorEvent){  
  22.       console.log('client side error',ex.message);  
  23.     }  
  24.     else{  
  25.       console.log('server side error',ex.message);  
  26.     }  
  27.    return  throwError('something went wrong');  
  28.   }  
  29. }  

So first, import HttpErrorResponse @angular/common/http

And after that, create the handleError method in which we will check for type of error. If it is a type of error event, then there will be an error which is from client-side; else the error will be from server-side.

And finally, we are making a call of this method using pipe on our getAllTaskWithFullResponse method and calling catchError which can be imported from ‘rxjs/operators'.

We can use this handleError method with any method from the task.service.ts file.

Using retry()

Sometimes you might have an error due to network interruptions on your mobile phone. These errors simply go away automatically if we try again. The RxJS library will give us a very simple solution to these problems, that is using retry, which can also be imported from ‘rxjs/operators'. In order to use these retry operators, modify your service, as shown below.

  1. import { Task } from './task';  
  2. import { Injectable } from '@angular/core';  
  3. import { HttpClient, HttpErrorResponse } from '@angular/common/http';  
  4. import { throwError, Observable } from 'rxjs';  
  5. import { catchError, retry } from 'rxjs/operators';  
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class TaskService {  
  10. url:string='https://rkdemotask.herokuapp.com/tasks/';  
  11.   constructor(public _http:HttpClient) { }  
  12.   getAllTaskWithFullResponse(){  
  13.     return this._http.get(this.url,{observe:'response'}).  
  14.     pipe(  
  15.       catchError(this.handleError)  
  16.     );  
  17.   }  
  18.   getAllTask(){  
  19.     return this._http.get<Task>(this.url).pipe(  
  20.       retry(3),  
  21.       catchError(this.handleError)  
  22.     );  
  23.   }  
  24.     
  25.   private handleError(ex:HttpErrorResponse){  
  26.     if(ex.error instanceof ErrorEvent){  
  27.       console.log('client side error',ex.message);  
  28.     }  
  29.     else{  
  30.       console.log('server side error',ex.message);  
  31.     }  
  32.    return  throwError('something went wrong');  
  33.   }  
  34. }  

So now, to check whether retry is working or not, I will turn off the wi-fi connection and check how many times it will make an HTTP request and after that, it will give us error message.

Explore Important Features Of HTTP Client With RxJs Operators 

So, as we can see, it will try for 3 more times before displaying the error message.

Search Using Debouncing

Assume the use case in which we want to create a search application for which we are passing every key stroke to our back end / web API to get the result from the server. Sending each and every keystroke to the back end would be expensive. It’s always a better solution that we can pass parameter to our back end only after the user stops typing. Yes, that’s very easy using RxJs Operators.

We will be using npm package search feature to perform a search operation. Below is the html,

  1. <input (keyup)="search($event.target.value)" id="name" placeholder="Search"/>  
  2.   
  3. <ul>  
  4.   <li *ngFor="let package of packages | async">  
  5.     <b>{{package.name}} v.{{package.version}}</b> -  
  6.     <i>{{package.description}}</i>  
  7.   </li>  
  8. </ul>  

This is an ideal html design of search application, which I used on the input box to take input from the user and an unordered list to display its result. As I told you before I am using npm package search services which will return name, version and description, which I am binding to li.

Below is the code snippet for typescript,

  1. import { Component, OnInit } from '@angular/core';  
  2. import { NpmserachService, NpmPackageInfo } from '../npmserach.service';  
  3. import { Subject, Observable } from 'rxjs';  
  4. import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';  
  5.   
  6. @Component({  
  7.   selector: 'app-demo',  
  8.   templateUrl: './demo.component.html',  
  9.   styleUrls: ['./demo.component.css']  
  10. })  
  11. export class DemoComponent implements OnInit {  
  12. public search_subject=new Subject<string>();  
  13. public packages:Observable<NpmPackageInfo[]>;  
  14.   constructor(public _data:NpmserachService) { }  
  15.   
  16.   search(searchTerm:string){  
  17.     this.search_subject.next(searchTerm);  
  18.   }  
  19.   ngOnInit() {  
  20.     this.packages=this.search_subject.pipe(  
  21.       debounceTime(1000),  
  22.       distinctUntilChanged(),  
  23.       switchMap(data=>this._data.search(data))  
  24.     );  
  25.   }  
  26. }  

I had created NpmserachService for making http call and NpmPackageInfo interface to provide data structure.

Here in the above code snippet, I am using Three RxJs Operators:

  1. debounceTime - It will wait for the user to stop typing (In our case 1 second)
  2. distinctUntilChanged - It will wait until the search term is changed
  3. switchMap - Finally, it will send the search term to service to make an HTTP request.

Below is the snippet for NpmsearchService,

  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { throwError, Observable, of } from 'rxjs';  
  4. import { catchError, retry,map } from 'rxjs/operators';  
  5.   
  6. export interface NpmPackageInfo {  
  7.   name: string;  
  8.   version: string;  
  9.   description: string;  
  10. }  
  11.   
  12. @Injectable({  
  13.   providedIn: 'root'  
  14. })  
  15. export class NpmserachService {  
  16. public url:string="https://npmsearch.com/query?q=";  
  17.   constructor(public _http:HttpClient) { }  
  18.   public search(searchTerm:string):Observable<NpmPackageInfo[]>{  
  19.     if (!searchTerm.trim()) { return of([]); }  
  20.    return this._http.get(this.url+searchTerm).pipe(  
  21.      map((data:any)=>{  
  22.       return data.results.map(  
  23.         entry=>({  
  24.             name:entry.name[0],  
  25.             version:entry.version[0],  
  26.             description:entry.description[0]  
  27.         } as NpmPackageInfo)  
  28.       );  
  29.      })  
  30.    );  
  31.   }  
  32. }  

Let's check if it is working or not, whether it will make call for each and every key stroke or if it will only make the call to the back-end after the user stops typing.

Explore Important Features Of HTTP Client With RxJs Operators 

In the above snapshot, although I typed 3 characters, it had made only one call to the back-end. Now, on the second screen, I will remove the 2 characters but it will make only one call to the back-end.

Explore Important Features Of HTTP Client With RxJs Operators 

That’s it! I hope I have made reading worth your time.


Similar Articles