RxJS Observables And Server Communication Using Httpclient

Introduction

 
In this article, we are going to explore the concept of RxJS Observables and server communication using HttpClient.
 

RxJS

 
RxJS is a reactive streams library used to work with asynchronous streams of data. It is a third-party library used by the Angular team.
 
Observables, in RxJS, are used to represent asynchronous streams of data. Observables are a more advanced version of Promises in JavaScript. 
 

Why do we use RxJS Observables?

 
Angular team has recommended Observables for asynchronous calls because of the following reasons:
  • Observables can be cancellable where Promises are not cancellable. If an HTTP response is not required, observables allow us to cancel the subscription whereas promises execute either success or failure callback even if we don’t need the result.
  • Promises emit a single value whereas observables (streams) emit many values.
  • Observables support functional operators such as map, filter, reduce, etc.

Observables and Promises

 
They both provide us with abstractions that help us deal with the asynchronous nature of applications. But both have the below differences:
 
 Promises  Observables
 Emits a single value at a time Emits multiple values over the period of time.
They get executed immediately after creation. So, not Lazy.
Thy is not executed until we subscribe to them using the subscribe() method. So, they are Lazy. 
 They are not cancellable.  They have subscriptions that are cancellable with Unsubscribe() method.
 Push errors to the child's promises.  Deliver errors to the subscriber.
 
Now let's see how to create and use an observable in Angular...
 
Open app.component.ts and add below line of code:
  1. import { Component } from '@angular/core';  
  2. import { Observable } from 'rxjs';  
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   data: Observable<number>;  
  10.   myArray: number[] = [];  
  11.   errors: boolean;  
  12.   finished: boolean;  
  13.   fetchData() {  
  14.     this.data = new Observable(observer => {  
  15.       setTimeout(() => { observer.next(10); }, 1000),  
  16.         setTimeout(() => { observer.next(20); }, 2000),  
  17.         setTimeout(() => { observer.complete(); }, 3000);  
  18.     });  
  19.     const sub = this.data.subscribe((value) => this.myArray.push(value),  
  20.       error => this.errors = true,  
  21.       () => this.finished = true);  
  22.   }  
  23. }  
Line 2: imports Observable class from rxjs module
 
Line 09: data is of type Observable which holds numeric values
 
Line 13: fetchData() is invoked on click of a button
 
Line 14: A new Observable is created and stored in the variable data
 
Line 15-17: next() method of Observable sends the given data through the stream. With a delay of 1,2 and 3 seconds, a stream of numeric values will be sent. Complete() method completes the Observable stream i.e., closes the stream.
 
Line 19: Observable has another method called subscribe which listens to the data coming through the stream. The subscribe () method has three parameters. The first parameter is a success callback that will be invoked upon receiving successful data from the stream. The second parameter is an error callback that will be invoked when Observable returns an error. The third parameter is a complete callback that will be invoked upon successful streaming of values from Observable i.e., once complete() is invoked. Here, upon a successful response, the data is pushed to the local array called myArray, if any error occurs, a Boolean value called true is stored in the error variable and upon complete(), will assign a Boolean value true in a finished variable.
 
Now add the below line of code in app.component.html:
  1. <b> Using Observables!</b>  
  2. <h6 style="margin-bottom: 0">VALUES:</h6>  
  3. <div *ngFor="let value of myArray"> {{ value }}</div>  
  4. <div style="margin-bottom: 0">ERRORS: {{ errors }}</div>  
  5. <div style="margin-bottom: 0">finished: {{ finished }}</div>  
  6. <button style="margin-top: 2rem;" (click)="fetchData()">Fetch Data</button>  
Line 03: ngFor loop is iterated on myArray, which will display the values on the page.
 
Line 04: {{ errors }} will render the value of errors property if any
 
Line 05: Displays finished property value when complete() method of Observable is executed
 
Line 06: Button click event is bound with fetchData() method which is invoked and creates an observable with a stream of numeric values.
 
Now build and execute the application. You will see the below output screen:
 
Now let's start with the server communication using HttpClient.
 
Server communication using HttpClient
  • Most front-end applications communicate with backend services using HTTP Protocol. When we make calls to an external server, we want our user to continue to be able to interact with the page. That is, we don’t want our page to freeze until the HTTP request returns from the external server. So, all HTTP requests are asynchronous.
  • We need to use HttpClient from @angular/common/HTTP to communicate with backend services. 
  • We need to import HttpClientModule from @angular/common/HTTP in the module class to make HTTP service available to the entire module. Import HttpClient service class into a component’s constructor. We can make use of HTTP methods like get, post, put, and delete.
  • JSON is the default response type for HttpClient. 
Making a GET request:
 
The following statement is used to fetch data from a server,
  1. this.http.get(url)  
http.get by default returns an observable.
 

Summary

 
In this article, we explored the concept of RxJS Observables and server communication using HttpClient. Also, we looked into the difference between Promise and Observable. I hope you liked the article. Until next time, happy reading! Cheers