Author avatar

Gaurav Singhal

Using HTTP with RxJS Observables

Gaurav Singhal

  • Jul 25, 2019
  • 10 Min read
  • Jul 25, 2019
  • 10 Min read
Languages Frameworks and Tools


Our web application responds asynchronously. This means that we can request many things at a time to our web application. Requests are met, in our web application, on a first come first served basis; after many requests, it provides a response to each request in its own contained thread.

Asynchronous web revolutionizes how web applications behave. It allows us to never wait for the operation to complete. Instead, it executes all operations in the first GO only. The result of each operation will be handled once the result is available.

How does a web application work on an asynchronous way? How can we implement it using Angular 7?

By the end of this guide, you will have a basic understanding of what RxJS is and how asynchronous functionality is done in the web application. This way, you can learn how to use it in real-world applications.

The RxJS

Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change.

RxJS Library

RxJS (Reactive Extensions for JavaScript) is a library, which allows you to work in asynchronous data programing.

RxJS provides an implementation of the Observable type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables.

These utility functions can be used for:

  • Converting existing code for async operations into observables.
  • Iterating through the values in a stream.
  • Mapping values to different types.
  • Filtering streams.
  • Composing multiple streams.

RxJS Observable

Observable is here to fulfill your dreams of working in a way where you can subscribe how it will work and interact with different streams. We can call observable the blueprint of RxJS. It will collect new values and multiple events to work. In the previous version of Angular, we were using Promises to handle requests but we are no longer using it because Promises are not able to work on multiple events. RxJS Observable not only works like promises but can accomplish even more.

Asynchronous pattern operations happen because there is no need to block while waiting for the Observable to emit objects. Instead, it creates a protector, in the form of an observer, that stands ready to react appropriately at whatever future time the Observable does.

RxJS Operators

Operators are the function that is built and creates new observables. Different operators are present in RxJS observable like map(), filter(), Concat(), and merge().

Use of Operators in RxJS:

  • It has configuration options.
  • It returns a function that takes a source observable. When returned to the function, the operators observe the data observables, deduce the value, and transform them.
  • The operator is able to create new observables of the transformed values.

Error Handling

To handle exceptions on subscriptions, catcherror() function is used. “catcherror()” function handles any damage to our Angular application whenever a response to a request fails.

We are using an API to request our data. Due to some errors, if API fails to respond then it will be handled in an observable that subscribes the error function.

Note: I am using Angular 7 for the examples below.

Getting Started

To install RXJS for your Angular application, use the following command.

1npm install rxjs

The Http Client is available from the @angular/common/http module, starting with Angular 4.3+, and replaces the old HTTP client that was available from the @angular/http package. It offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers. Some additional benefits of HttpClient include test-ability features, typed request and response objects, request and response interception, Observable APIs, and streamlined error handling. We are using HttpClient to fetch data from the server to our application.

The Http Header in @angular/common/HTTP offers a simplified header to HTTP API for Angular applications. Many servers require extra headers for save operations. For example, they may need a "Content-Type" header to declare the MIME type of the request body explicitly. Or, perhaps, the server requires an authorization token.

Import HTTP Client and HTTP Header as given below.

1import { HttpClient, HttpHeaders } from '@angular/common/http';

Jumping into the Code

Now that everything is installed on your system, let us jump into a simple example code.

Step 1: Start a New Project

Since Angular is a framework, we need to follow some standards of the framework.

Let's create a new project in RxJS; I have named my project as RxJS_observable.

1ng new RxJS_observable

Step 2: Creating Our First Angular 7 Application for RxJS Asynchronous Process

Setting Up HttpClient

The first step is to import the HttpClientModule in src/app/app.module.ts.

1import { HttpClientModule } from '@angular/common/http';
3    declarations: [
4        AppComponent
5    ],
6imports: [BrowserModule,HttpClientModule],
7bootstrap: [AppComponent]
9export class AppModule { }

Next, let's create a class model. I have named my class name as country.

1ng generate class country

After the class is generated, let's add some objects:

1export class Country {
2    id: number;
3    name: string;
4    capital:string;

For requests, we need to call the API for the service file that we need in Angular. I have named the class name apicall.

1ng generate service apicall

After you’ve generated apicall.service.ts, import the HTTP client, and initialize in the constructor, as shown below.

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

In Constructor:

1constructor(private httpClient: HttpClient) {}

Import RxJS in Services

In services, we must import RxJS, as given below, for Asynchronous processes.

1import * as Rx from "rxjs/Rx";
2import { from, Observable } from 'rxjs';

You can use the following command to run for Angular.

1ng serve

Step 3: Our First Requests to Search Capital by Name

An application working on a set of requests using request methods indicates the desired action to perform for a given resource.

To request to search capitals by name, follow the below code steps:


1import { Injectable } from '@angular/core';
2import { HttpClient } from '@angular/common/http';
3import * as Rx from "rxjs/Rx";
4import { from, Observable, throwError } from 'rxjs';
5import { map, catchError } from 'rxjs/operators';
7  providedIn: 'root'
9export class ApicallService {
10  constructor(private httpClient: HttpClient) {}
12  searchCountryByName(name: string): Observable<Country[]>{
13    let headers: HttpHeaders = new HttpHeaders();
14    headers = headers.append('Accept', 'application/json');
15    headers = headers.append(
16      'X-RapidAPI-Key',
17      '1108554cc1mshf11c17c4fea2b3dp179054jsn2446fb7a8965'
18    );
19    return this.httpClient.get(
20      `` + name, 
21       {headers: headers}
22      ).pipe(
23           map((data: Country[]) => {
24             return data;
25           }), catchError( error => {
26             return throwError( 'Capital not found!' );
27           })
28        )
29    }

In the above code, we created the searchCountryByName() method to call the API. We are calling the HTTP GET method to get a list of all data by capital name. We requested the API URL,, while passing name to get a response map to the Country class using the map key. It will return a response and map to the object. If the capital is not found then it will throw a not found exception, which will throw an error, “Capital not found!”. In the header we append the API-key and Content-type.


1export class AppComponent {
3  constructor(public http: HttpClient, private apiService: ApicallService){}
5  ngOnInit(){
6  }
8  name:string;
9  searchCapital() {
10    this.apiService
11    .searchCountryByName(
12    .subscribe((data:Country[]) => {
13      console.log(data);
14      this.countries = data;
15    });
16  }

In the above code, we created the searchCapital() method. It is an action method, which is working on the click button, and it starts to search the capitals by name. Here, we call the searchCountryByName() method from ApiCallservice; it subscribes the country class to collect data.


2  <label>Capital Name*</label>
3  <input type="text" placeholder="Enter Capital" [(ngModel)]="name" />
4  <button  type="submit" (click)="searchCapital()">Search</button>
8  <thead>
9    <tr>
10      <th>Name</th>
11      <th>Salary</th>
12    </tr>
13  </thead>
14  <tbody>
15    <tr *ngFor="let country of countries">
16      <td>{{}}</td>
17      <td>{{}}</td>
18    </tr>
19  </tbody>

In the above code, we created Textfield (Input) where we entered a capital name to search and created a search button where we call searchCapital() method which is present in app.component.ts. The table is designed to show the found data list.


RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that make it easier to compose asynchronously.

RxJS Observables work on multiple values and multiple events.

Here are some of the ways that you can expand your code for learning purposes:

  • Installation of RxJS in Angular 7.
  • Import RxJS in an Angular application.
  • Learn how to call an API using HTTP Methods.
  • Data binding to the model.
  • Map the response and Bind with UI and model.
  • Create an HTTP request using HTTPClient in services to access API.
  • Create an HTTP header using HTTPHeader in services to append headers in an application.

Now you should have an idea of how we use the web application in Angular to work asynchronously.