AngularJS 2.0 From The Beginning - Observables - Day Nineteen

In this article, we will discuss about observables pattern in both Javascript and also on Angular js 2.0.

I am here to continue the discussion around AngularJS 2.0. In my previous article, I have already discussed about the http module including get and post method calling in Angular 2.0. Now, in this article, we will discuss about the observables concept in Angular 2.0. In case, you did not have a look at the previous articles of this series, go through the links mentioned below.

We already discussed that in Angular 2.0, there are many new features introduced in Angular 2.0. An exciting new feature used with Angular is Observable. This isn't an Angular specific feature but rather a proposed standard for managing async data that will be included in the release of ES7. Observables open up a continuous channel of communication in which multiple values of data can be emitted over time. From this, we get a pattern of dealing with data by using array-like operations to parse, modify and maintain the data. Angular uses Observables extensively - you'll see them in the HTTP service and the event system.

In version 2.0, Angular mainly introduces the reactive programming concept based on the observables for dealing the asynchronous processing of data. In Angular 1.x, we basically used promises to handle the asynchronous processing. But still in Angular 2.0, we can still use the promises for the same purpose. The main concept of reactive programing is the observable element which is related to the entity that can be observed. Basically, at normal look, promises and observables seem very similar to each other. Both of them allow us to execute asynchronous processing, register callbacks for both successful and error responses, and also notify or inform us when the result is there.

How to define Observables

Before going into detailed example of observables, first we need to understand how to define an observable object. To create an observable, we can use the create method of the Observable object. A function must be provided as parameter with the code to initialize the observable processing. A function can be returned by this function to cancel the observable.

  1. var observable = Observable.create((observer) =>  
  2. {  
  3.     setTimeout(() => {  
  4.         observer.next('some event');  
  5.     }, 500);  
  6. });  

Similar to promises, observables can produce several notifications using different methods from the observer.

  1. next
    Emit an event. This can be called several times.

  2. error
    Throw an error. This can be called once and will break the stream. This means that the error callback will be immediately called and no more events or completion can be received.

  3. complete
    Mark the observable as completed. After this, no more events or errors will be handled and provided to corresponding callbacks.

Observables allow us to register callbacks for previously described notifications. The subscribe method tackles this issue. It accepts three callbacks as parameters,

  • The onNext callback that will be called when an event is triggered.
  • The onError callback that will be called when an error is thrown.
  • The onCompleted callback that will be called when the observable completes.

Observable specificities

Observables and promises have many similarities, and inspite of that, observables provide us some new specifications like below -

  • Lazy
    An observable is only enabled when a first observer subscribes. This is a significant difference compared to promises. Due to this, processing is provided to initialize a promise is always executed even if no listener is registered. This means that promises don’t wait for subscribers to be ready to receive and handle the response. When creating the promise, the initialization processing is always immediately called. Observables are lazy so we have to subscribe a callback to let them execute their initialization callback.

  • Execute Several Times
    Another particularity of observables is that they can be triggerred several times unlike promises which can’t be used after they were resolved or rejected.

  • Canceling Observables
    Another characteristic of observables is that they can be cancelled. For this, we can simply return a function within the initialization call of the Observable.create function. We can refactor our initial code to make it possible to cancel the timeout function.

Error Handling

If something unexpected arises, we can raise an error on the Observable stream and use the function reserved for handling errors in our subscribe routine to see what happened.

  1. import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';  
  2. import { Observable } from 'rxjs/Observable';  
  3.   
  4. @Component({  
  5.     moduleId: module.id,  
  6.     selector: 'home-page',  
  7.     templateUrl: 'app.component.homepage.html'  
  8. })  
  9.   
  10. export class HomePageComponent implements OnInit {  
  11.   
  12.     private data: Observable<Array<number>>;  
  13.     private values: Array<number> = [];  
  14.     private anyErrors: boolean;  
  15.     private finished: boolean;  
  16.     private status: string;  
  17.   
  18.     constructor() {  
  19.     }  
  20.   
  21.     ngOnInit(): void {  
  22.   
  23.     }  
  24.   
  25.     private onClick(): void {  
  26.         let self = this;  
  27.         this.data = Observable.create(observer => {  
  28.             setTimeout(() => {  
  29.                 observer.next(10);  
  30.             }, 500);  
  31.   
  32.             setTimeout(() => {  
  33.                 observer.next(100);  
  34.             }, 1000);  
  35.   
  36.             setTimeout(() => {  
  37.                 observer.complete();  
  38.             }, 2000);  
  39.             this.status = "Started";  
  40.         });  
  41.   
  42.         let subscription = this.data.subscribe(  
  43.             (value) => {  
  44.                 let data: any = { val: value };  
  45.                 self.values.push(data);  
  46.             },  
  47.             error => self.anyErrors = true,  
  48.             () => self.finished = true  
  49.         );  
  50.     }  
  51.   
  52.     private onClick1(): void {  
  53.         let self = this;  
  54.         this.data = Observable.create(observer => {  
  55.             setTimeout(() => {  
  56.                 observer.next(10);  
  57.             }, 500);  
  58.   
  59.             setTimeout(() => {  
  60.                 observer.next(100);  
  61.             }, 1000);  
  62.   
  63.             setTimeout(() => {  
  64.                 observer.complete();  
  65.             }, 2000);  
  66.             this.status = "Started";  
  67.         });  
  68.   
  69.         let subscription = this.data.forEach(  
  70.             (value) => {  
  71.                 let data: any = { val: value };  
  72.                 self.values.push(data);  
  73.             })  
  74.             .then(() => self.status = "Ended");  
  75.     }  
  76. }   
app.component.homepage.html
  1. <div>  
  2.     <h3>Observables Sample</h3>  
  3.     <b>Angular 2 Sample Component Using Observables!</b>  
  4.   
  5.     <h6 style="margin-bottom: 0">Count:</h6>  
  6.     <div *ngFor="let item of values">{{ item.val }}</div>  
  7.   
  8.     <h6 style="margin-bottom: 0">ERRORs:</h6>  
  9.     <div>Errors: {{anyErrors}}</div>  
  10.   
  11.     <h6 style="margin-bottom: 0">FINISHED:</h6>  
  12.     <div>Finished: {{ finished }}</div>  
  13.   
  14.     <h6 style="margin-bottom: 0">STATUS:</h6>  
  15.     <div>{{status}}</div>  
  16.   
  17.     <button style="margin-top: 2rem;" (click)="onClick()">Init Page</button>  
  18.     <error-page></error-page>  
  19. </div>  
app.component.error.ts
  1. import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';  
  2. import { Observable } from 'rxjs/Observable';  
  3.   
  4. @Component({  
  5.     moduleId: module.id,  
  6.     selector: 'error-page',  
  7.     templateUrl: 'app.component.error.html'  
  8. })  
  9.   
  10. export class ErrorComponent implements OnInit {  
  11.   
  12.     private data: Observable<Array<number>>;  
  13.     private values: Array<number> = [];  
  14.     private anyErrors: any;  
  15.   
  16.     constructor() {  
  17.     }  
  18.   
  19.     ngOnInit(): void {  
  20.   
  21.     }  
  22.   
  23.     private onClick(): void {  
  24.         let self = this;  
  25.         this.data = Observable.create(observer => {  
  26.             setTimeout(() => {  
  27.                 observer.next(10)  
  28.             }, 1500);  
  29.             setTimeout(() => {  
  30.                 observer.error('Hey something bad happened I guess');  
  31.             }, 2000);  
  32.             setTimeout(() => {  
  33.                 observer.next(50)  
  34.             }, 2500);  
  35.         });  
  36.   
  37.          let subscription = this.data.subscribe(  
  38.             (value) => {  
  39.                 let data: any = { val: value };  
  40.                 self.values.push(data);  
  41.             },  
  42.             error => self.anyErrors = "Ended"  
  43.         );  
  44.     }  
  45. }   
app.component.error.html
  1. <div>  
  2.     <h3>Observables Sample - Error handling</h3>  
  3.     <b>Angular 2 Component using Observables!</b>  
  4.   
  5.     <h5 style="margin-bottom: 0">VALUES</h5>  
  6.     <div *ngFor="let item of values">{{ item.val.toString() }}</div>  
  7.   
  8.     <h5 style="margin-bottom: 0">ERRORS</h5>  
  9.     <pre><code>{{anyErrors}}</code></pre>  
  10.   
  11.     <button style="margin-top: 2rem;" (click)="onClick()">Init Page</button>  
  12. </div>  
app.module.ts
  1. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from "@angular/forms";  
  4. import { HttpModule } from '@angular/http';  
  5.   
  6. import { HomePageComponent } from './src/app.component.homepage';  
  7. import { ErrorComponent } from './src/app.component.error';  
  8.   
  9. @NgModule({  
  10.     imports: [BrowserModule, FormsModule, HttpModule],  
  11.     declarations: [HomePageComponent, ErrorComponent],  
  12.     bootstrap: [HomePageComponent]  
  13. })  
  14. export class AppModule { }  
index.html
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Angular2 - Observables </title>  
  5.     <meta charset="UTF-8">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <link href="../resources/style/bootstrap.css" rel="stylesheet" />  
  8.     <link href="../resources/style/style1.css" rel="stylesheet" />  
  9.     <!-- Polyfill(s) for older browsers -->  
  10.     <script src="../resources/js/jquery-2.1.1.js"></script>  
  11.     <script src="../resources/js/bootstrap.js"></script>  
  12.   
  13.     <script src="../node_modules/core-js/client/shim.min.js"></script>  
  14.     <script src="../node_modules/zone.js/dist/zone.js"></script>  
  15.     <script src="../node_modules/reflect-metadata/Reflect.js"></script>  
  16.     <script src="../node_modules/systemjs/dist/system.src.js"></script>  
  17.     <script src="../systemjs.config.js"></script>  
  18.     <script>  
  19.         System.import('app').catch(function (err) { console.error(err); });  
  20.     </script>  
  21.     <!-- Set the base href, demo only! In your app: <base href="/"> -->  
  22.     <script>document.write('<base href="' + document.location + '" />');</script>  
  23. </head>  
  24. <body>  
  25.     <home-page>Loading</home-page>  
  26. </body>  
  27. </html>   
main.t
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2.   
  3. import { AppModule } from './app.module';  
  4.   
  5. const platform = platformBrowserDynamic();  
  6. platform.bootstrapModule(AppModule);  
Now, run the code and get the output as below.