Basics Of Angular And Its Versions - Part Five

Before reading this article, please go through my previous articles for better understanding,

To deal with asynchronous data Angular provides two models of approaches, we can either use Promises or Observables.

Promises

  • Emits a single value
  • Cannot be canceled
  • Not Lazy

Even after we comment the then() method but the service call still be issued to the web API call over the network. In order to get the data from service call we have to handle it using then() method.

  • Supports async/await
  • Easy readable source code when we use try/catch & async/await
  • Promises require the caller to have access to the original function that returned the promise in order to have a retry capability.

By default, Angular built-in HTTP services return Observable. To return Promise as a response to the called method, first, we have to convert the response to Promise using toPromise() method.

Sample code snippet for Promise call,

  1. request(req: Request): Promise<any> {  
  2.         return this.http.request(req)  
  3.             .toPromise()  
  4.             .then((response: Response) => {  
  5.                 return response.text().length ? response.json() : null;  
  6.             })  
  7.             .catch((error: any) => this.handleError(error, req));  
  8.     } 

To support toPrimise() method, first we have to import toPromise() from rxjs as below,

import 'rxjs/add/operator/toPromise';

Observables

  • Emits multiple values over a period of time.
    We can think of an observable like a stream which emits multiple values over a period of time and the same call back function is called for each item emitted. So, with an observable, we can use the same API to handle asynchronous data whether the data is emitted a single value or multiple values over a period of time.
  • Can be canceled by using unsubscribe() method

  • Lazy
    Here lazy means the observable will not be called until we subscribe to the observable using the subscribe() method. If we comment the subscribe method and then try to call the API method then the service call will not be issued, to issue the API call we have to subscribe to the observable at any cost, that is why we call it as a lazy.
  • Supports many powerful operators, like filter, map, reduce, retry, retryWhen, forEach and like other operators.

  • Can use Reactive Extensions

  • An array whose items arrive asynchronously over time

By default, Angular built-in HTTP services return Observable. Observable is a more powerful way of handling HTTP asynchronous requests. We can convert the promised call back to Observable also by using Observable.from promise(HTTP call) method.

Sample code snippet for Observable call,

  1. import { Http, Response } from '@angular/http';  
  2. import { Injectable } from '@angular/core';  
  3. import { Observable } from 'rxjs/Observable';  
  4.   
  5. @Injectable()  
  6. export class EmployeeService {  
  7.     constructor(primate _http: Http)  
  8.     getEmployees(): Observable<any> {  
  9.        return this._http.get("http://localhost:1234/api/employees")  
  10.             .map((response: Response) => <any[]>response.json())  
  11.             .catch();  
  12.     }  

We can convert the Promise call to Observable by using fromPromise() method, as below.

  1. request(req: Request): Promise<any> {  
  2.         return this.http.request(req)  
  3.             .toPromise()  
  4.             .then((response: Response) => {  
  5.                 return response.text().length ? response.json() : null;  
  6.             })  
  7.             .catch((error: any) => this.handleError(error, req));  
  8.     }  
  9.   
  10. getDetails(id: number): Observable<Array<any>> {  
  11.         return Observable.fromPromise(request(req));  

To support Observable, we have to import from rxjs, as below.

import { Observable } from 'rxjs/Rx';

I would appreciate your valuable comments. Happy reading :)