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

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.

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

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. @Injectable()
  5. export class EmployeeService {
  6. constructor(primate _http: Http)
  7. getEmployees(): Observable<any> {
  8. return this._http.get("http://localhost:1234/api/employees")
  9. .map((response: Response) => <any[]>response.json())
  10. .catch();
  11. }
  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. getDetails(id: number): Observable<Array<any>> {
  10. return Observable.fromPromise(request(req));
  11. }

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

import { Observable } from 'rxjs/Rx';

I would appreciate your valuable comments. Happy reading :)