Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Using HTTP with RxJS Observables

Jul 25, 2019 • 10 Minute Read

Introduction

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.

      npm 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.

      import { 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.

      ng 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.

      import { HttpClientModule } from '@angular/common/http';
@NgModule({
    declarations: [
        AppComponent
    ],
imports: [BrowserModule,HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule { }
    

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

      ng generate class country
    

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

      export class Country {
    id: number;
    name: string;
    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.

      ng generate service apicall
    

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

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

In Constructor:

      constructor(private httpClient: HttpClient) {}
    

Import RxJS in Services

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

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

You can use the following command to run for Angular.

      ng 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:

apicall.service.ts

      import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as Rx from "rxjs/Rx";
import { from, Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class ApicallService {
  constructor(private httpClient: HttpClient) {}

  searchCountryByName(name: string): Observable<Country[]>{
    let headers: HttpHeaders = new HttpHeaders();
    headers = headers.append('Accept', 'application/json');
    headers = headers.append(
      'X-RapidAPI-Key',
      '1108554cc1mshf11c17c4fea2b3dp179054jsn2446fb7a8965'
    );
    return this.httpClient.get(
      `https://restcountries-v1.p.rapidapi.com/capital/` + name, 
       {headers: headers}
      ).pipe(
           map((data: Country[]) => {
             return data;
           }), catchError( error => {
             return throwError( 'Capital not found!' );
           })
        )
    }
}
    

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, https://restcountries-v1.p.rapidapi.com/capital/name, 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.

app.component.ts

      export class AppComponent {
  
  constructor(public http: HttpClient, private apiService: ApicallService){}

  ngOnInit(){
  }

  name:string;
  searchCapital() {
    this.apiService
    .searchCountryByName(this.name)
    .subscribe((data:Country[]) => {
      console.log(data);
      this.countries = data;
    });
  }
}
    

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.

app.component.html

      <form>
  <label>Capital Name*</label>
  <input type="text" placeholder="Enter Capital" [(ngModel)]="name" />
  <button  type="submit" (click)="searchCapital()">Search</button>
</form>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let country of countries">
      <td>{{country.name}}</td>
      <td>{{country.capital}}</td>
    </tr>
  </tbody>
</table>
    

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.

Conclusion

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.