Tuesday, 20 February 2018

Angular - Promises and Observables

Angular — Promises basics

Promise introduction
Click here

 1- Create deferred object
The deferred object controls the state of the promise. We can trigger three resolutions: resolve, reject and notify. In the following steps we will see how it relates to the promise setup.

This is how you create a deferred object:

var deferred = $q.defer();

2 Setup promise
In order to use the deferred object we need to setup the promise handlers before. This will be the code executed for each resolution. The scenarios are: success, failure and progress notification. The promise object is a property of the deferred object.

var promise = deferred.promise;

//basic version
  .catch(fnFailure) //optional
  .finally(fnAlways) //optional

//advanced version
promise.then(fnSuccess, fnFailure, fnNotification)
  .catch(fnFailure) //optional
  .finally(fnAlways) //optional

3 Defer resolution
Once we have created the deferred object and setup the promise, we can execute our asynchronous processing and trigger the promise with the final resolution.
deferred.resolve(resultObj); //triggers fnSuccess
deferred.reject(reasonObj); //triggers fnFailure
deferred.notify(progressObj); //triggers fnNotification 

Advanced $http promise usage

This example uses promises to handle $http calls behind a Service. More complex handling can be added to the Service afterwards.
app.factory("Movies", function($http, $q) {
  return {
    get: function() {
        var deferred = $q.defer();
        return deferred.promise;
app.controller("MoviesCtrl", function($scope, Movies) {
      $scope.movies = data;

When moving data retrieval to a Service we want to keep error handling and communication details encapsulated into the Service so only data is returned to consumers and not the response object     (Eg: response.status)

Angular — Introduction to Reactive Extensions (RxJS)

Reactive Extensions for JavaScript (RxJS) is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or in the server-side using Node.js.

merge- Turn multiple observables into a single observable.

from- Turn an array, promise, or iterable into an observable.

throw- throw(error: any, scheduler: Scheduler): Observable

map- Apply projection with each value from source.

mapTo- Map emissions to constant value.

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { environment as env } from '../../../environments/environment';

export class StoreService {
headers: Headers;
constructor(private http: Http) {
this.headers = new Headers({ 'content-type': 'application/json' });

GetProducts(): Observable<Product[]> {
return this.http.get(env.apiAddress + '/store').map((res) => {
return res.json();
}).catch((err) => Observable.throw(err));

SaveCart(cart: Cart): Observable<string> {
return this.http.post(env.apiAddress + '/store/cart', JSON.stringify(cart),
{ headers: this.headers }).map((res) => {
return res.json();
}).catch((err) => Observable.throw(err));


Post a Comment


ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)