Promises in angular 2 example

In this video we will discuss using Promises instead of Observables in Angular.

In Angular we can use either Promises or Observables. By default the Angular Http service returns an Observable. To prove this, hover the mouse over the get() method of the Http service in employee.service.ts file. Notice from the intellisense, that it returns Observable<Response>

We discussed Observables in Part 27 of Angular 2 tutorial. To use Promises instead of Observables we will have to first make a change to the service to return a Promise instead of an Observable.

In employee.service.ts file modify getEmployeeByCode() method as shown below. The changes are commented so they are self-explanatory

import { Injectable } from'@angular/core';

import { IEmployee } from'./employee';

import { Http, Response } from'@angular/http';

import { Observable } from'rxjs/Observable';

import'rxjs/add/operator/map';

import'rxjs/add/operator/catch';

import'rxjs/add/Observable/throw';

// import
toPromise operator

import'rxjs/add/operator/toPromise';

@Injectable()

exportclass
EmployeeService {

constructor(private _http:
Http) { }

getEmployees():
Observable<IEmployee[]> {

returnthis._http.get('http://localhost:24535/api/employees')

.map((response: Response) =>
<IEmployee[]>response.json())

.catch(this.handleError);

}

// Notice we
changed the return type of the method to Promise<IEmployee>