Consuming RESTful Service with HttpClient and RxJS

( 0 users )

REST or HTTP based services are the primary requirements of single page applications to retrieve the data and gel into the web application. Angular offers its inbuilt http client service which wraps the major functions for requesting the data from server where REST service is hosted.

Angular provides HttpClient for this purpose which is packaged under @angular/common/http. Before we can use HttpClient, we have to import HttpClientModule in our main application module.

HttpClient is best consumed when used with Observables. You must be asking a question - What is an Observable here? An Observable is simply a collection of future events which arrives asynchronously over time.

RxJS

Observables are pretty much similar to promise or callbacks but the main advantage is they are lazy loaded. Observables will not be called till the time any subscriber invoked on it. Feel free to play around at RxMarbles website http://rxmarbles.com to get to know how values are observed over time.

Building our example app

Let us start with an example. Here we are building a simple survey which will ask a question and user can choose from one of the four option. We will get our survey data from our Http service as JSON. Full working example is here - StackBlitz - Angular Http Service and Observables

Create a survey interface

export interface ISurvey{
question:string;
choices: string[];
}

Our Survey Data

Let's add couple of questions in our json survey data which we will request from our http service. You can add more later.

Our Survey Service

We will now add our survey service class which will provide data interaction operations to our survey class. Now, to make survey service injectable we'll import Injectable from '@angular/core' and decorate our component with @Injectable().

@Injectable()
export class SurveyService {
..
}

Injecting HttpClient into Survey service

Add http functionality by importing HttpClient from '@angular/common/http' and inject the HttpClient in our constructor:

The RxJS Retry operator

If your want to retry your http requests on case you receives error in your http response, then there is a retry operator (provided by RxJs) that you can use to resubscribe to the observable to re-invoke it for a number of times.

This following code will retry 3 times as http service continues to receive any http error.