Explore important features of HTTP Client with RxJs Operators

Hello Everyone,

In this article, I will be covering major concepts regarding HTTP Client. I know at first it will sound like an old topic but believe me you will definitely find some new features with this article.

What to expect from the article?

· Starting from scratch calling web API (making get request)

· Displaying Full result with Headers, Code, Status, Status Text, etc

· Dealing with Error both (Server Side Errors and Client Side Errors)

· Some rxjs operators (like retry, catch errors, map etc)

· Search using debouncing

So, let’s dive with HTTP Client from the Scratch.

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

Generate Service and provide it in root

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

Command for generate Services using Angular Cli

ng g s task

then in order to use service in our application we first need to provide the services in general case 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 decorator in our newly created service.

@Injectable({

providedIn: ‘root’

})

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

Introduction to webAPI

Now before making call to my webAPI, I would like to give brief introduction about the webAPI and what it will return us?

url: https://rkdemotask.herokuapp.com/tasks/

GET: Fetch All Task and return Id,Title and Status

Below are 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 same.

Generate Task Class

We had created the class to provide data structure and storing the data which is returned by webAPI.

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

Creating Method In Service

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

Then we are having one method name getAllTask which will simply make http call to my web API and also return us all the tasks.

The second method getAllTaskWithFullResponse is almost a same method but it will return us the full response i.e. it will return us the response with headers, code, Stauts Text, Body etc where getAllTask will only return us the data. We can make full response to true by simply passing and observe flag with 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 methods.

Injecting Service to app.component.ts

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)

Only data (getAllTask)

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

Error Handling

So now let’s dive little bit deeper with HTTP Client and handle HTTP Errors. So 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 address or due to internal server error.

2. Client Side Error i.e. network error which in turns not allowing to make a call or some error because of rxjs operators.

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

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

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 type of error event then there will be an error which is from client side else error will be from server side.

And finally we are making 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 task.service.ts file.

Using retry()

Sometimes you might have an error due to network interruptions on your mobile phone, these type of error simply goes away automatically if we try again. The rxjs library will give us very simple solution to these problem is using retry, which can also imported from ‘rxjs/operators’. In order to use these retry operator modify your service as shown below,

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

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

Search Using Debouncing

Assume the use case, we want to create a search application for which we are passing every key stroke to our back end / web API to get result from server. Sending each and every keystroke to back end would be expensive. It’s always a better solution that we can pass parameter to our back end only after 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,

This is an ideal html design of search application, where I have used an input box to take an input from the user and unordered list to display its result. As I have mentioned before I am using npm package search services which will return us name, version and description as a result which I will be binding to list item.

Below is the code snippet for typescript,

I have created NpmserachService to make http call and NpmPackageInfo interface to provide data structure.

Here in 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 changed

3. switchMap : finally it will send the search term to service to make http request.

Below is the snippet for NpmsearchService,

To check whether it is working or not , and whether it is making call for each and every key stroke or it will only make the call to back end after user stops typing.

In above snap shot, although I have typed 3 characters, it had made only one call to back end, now in second screen I will remove the 2 characters but it will make only one call to the back end.

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

Jinal Shah is corporate trainer on different technology like node.Js, Angular,Ionic 2, BOT Framework etc.