AngularJS 2.0 From The Beginning - Observables With Form Modules - Day Twenty

I am here to continue the discussion around AngularJS 2.0. I already discussed about the basic concept of Reactive programming concept or observables in Angular 2.0. Now, in this article, we discuss about the observables concept with http module or form modules 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.

Observables vs Promises

Both Promises and Observables provide us with abstraction that helps us to deal with the asynchronous nature of our Applications. However, there are important differences between the two:

As seen in the example above, Observables can define both the setup and teardown aspects of asynchronous behavior.

Observables are cancellable.

Moreover, Observables can be retried, using one of the retry operators provided by the API, such as retry and retryWhen. On the other hand, Promises require the caller to have an access to the original function, which returned the Promise in order to have a retry capability.

Observable HTTP Events

A common operation in any Web Application is getting or posting the data to a Server. Angular Applications do this with Http library, which previously used Promises to operate in an asynchronous manner. The updated Http library now incorporates Observables to trigger the events and getting new data.  

Observables Array Operations

In addition to simply iterating over an asynchronous collection, we can perform other operations such as filter or map and many more as defined in the RxJS API. This is what bridges an Observable with the iterable pattern and lets us conceptualize them as collections.

Here are two really useful array operations - map and filter. What exactly do these do?

map will create a new array with the results of calling a provided function on every element in this array. In the example given below, we used it to create a new result set by iterating through each item and appending the word ‘Mr’ abbreviation in front of every employee's name.

filter will create a new array with all the elements that pass the test implemented by a provided function. Here, we have used it to create a new result set by excluding any user whose salary is below 20000. Now, when our subscribe callback gets invoked, the data it receives will be a list of JSON objects, whose id properties are greater than or equal to 20000 salary.

Note the chaining function style and the optional static typing, which comes with TypeScript, which we used in this example. Most importantly functions like filter return an Observable, as in Observables we get other Observables, which are similar to Promises. In order to use map and filter in a chaining sequence, we have flattened the results of our Observable, using flatMap. Since filter accepts an Observable and not an array, we have to convert our array of JSON objects from data.json() to an Observablestream. This is done with flatMap

To demonstrate the above concept, create the files given below with the code.
 
app.component.homepage.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2. import { Http, Response } from '@angular/http';  
  3. import 'rxjs/Rx';  
  4.   
  5. @Component({  
  6.     moduleId: module.id,  
  7.     selector: 'home-page',  
  8.     templateUrl: 'app.component.homepage.html'  
  9. })  
  10.   
  11. export class HomePageComponent implements OnInit {  
  12.   
  13.     private data: Array<any> = [];  
  14.   
  15.     constructor(private http: Http) {  
  16.     }  
  17.   
  18.     ngOnInit(): void {  
  19.     }  
  20.   
  21.     private loadData(): void {  
  22.         this.data = [];  
  23.         let self = this;  
  24.         this.http.request('http://localhost:5201/employee/getemployee')  
  25.             .flatMap((result) => result.json())  
  26.             .subscribe((result) => {  
  27.                 self.data.push(result);  
  28.             });  
  29.     }  
  30.   
  31.     private loadDataMap(): void {  
  32.         this.data = [];  
  33.         let self = this;  
  34.         this.http.request('http://localhost:5201/employee/getemployee')  
  35.             .flatMap((result) => result.json())  
  36.             .map((emp) => {  
  37.                 emp["Name"] = "Mr. " + emp["Name"];  
  38.                 return emp;  
  39.             })  
  40.             .subscribe((result) => {  
  41.                 self.data.push(result);  
  42.             });  
  43.     }  
  44.   
  45.     private loadDataFilter(): void {  
  46.         this.data = [];  
  47.         let self = this;  
  48.         this.http.request('http://localhost:5201/employee/getemployee')  
  49.             .flatMap((result) => result.json())  
  50.             .filter((emp) => emp["Salary"] <= 20000)  
  51.             .subscribe((result) => {  
  52.                 self.data.push(result);  
  53.             });  
  54.     }  
  55. }   
app.component.homepage.html
  1. <div>  
  2.     <h3>HTTP Module Sample - Get Data</h3>  
  3.     <div class="panel panel-default">  
  4.         <div class="panel-body">  
  5.             <table class="table table-striped table-bordered">  
  6.                 <thead>  
  7.                     <tr>  
  8.                         <th>Srl No</th>  
  9.                         <th>Alias</th>  
  10.                         <th>Employee Name</th>  
  11.                         <th>Date of Birth</th>  
  12.                         <th>Join Date</th>  
  13.                         <th>Department</th>  
  14.                         <th>Designation</th>  
  15.                         <th>Salary</th>  
  16.                     </tr>  
  17.                 </thead>  
  18.                 <tbody>  
  19.                     <tr *ngFor="let item of data">  
  20.                         <td>{{item.Id}}</td>  
  21.                         <td>{{item.Code}}</td>  
  22.                         <td>{{item.Name}}</td>  
  23.                         <td>{{item.DOB | date :'shortDate'}}</td>  
  24.                         <td>{{item.DOJ | date :'mediumDate'}}</td>  
  25.                         <td>{{item.Department}}</td>  
  26.                         <td>{{item.Designation}}</td>  
  27.                         <td>{{item.Salary |currency:'INR':true}}</td>  
  28.                     </tr>  
  29.                 </tbody>  
  30.             </table>  
  31.             <p>  
  32.                 <button class="btn btn-primary" (click)="loadData()">  
  33.                     Load All Data  
  34.                 </button>  
  35.                 <button class="btn btn-primary" (click)="loadDataMap()">  
  36.                    Load Data With Map  
  37.                 </button>  
  38.                 <button class="btn btn-primary" (click)="loadDataFilter()">  
  39.                     Load Data With Filter  
  40.                 </button>  
  41.             </p>  
  42.         </div>  
  43.     </div>  
  44. </div>   
app.module.ts
  1. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { ReactiveFormsModule } from "@angular/forms";  
  4. import { HttpModule } from '@angular/http';  
  5.   
  6. import { HomePageComponent } from './src/app.component.homepage';  
  7.   
  8. @NgModule({  
  9.     imports: [BrowserModule, ReactiveFormsModule, HttpModule],  
  10.     declarations: [HomePageComponent],  
  11.     bootstrap: [HomePageComponent]  
  12. })  
  13. export class AppModule { }   
main.ts
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2.   
  3. import { AppModule } from './app.module';  
  4.   
  5. const platform = platformBrowserDynamic();  
  6. platform.bootstrapModule(AppModule);   
index.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Angular2 - HTTP Module (GET) </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>   
Employee.cs (model class) 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace SampleAPI.Models.Sample  
  7. {  
  8.     public class Employee  
  9.     {  
  10.         public int Id { get; set; }  
  11.         public string Code { get; set; }  
  12.         public string Name { get; set; }  
  13.         public DateTime DOB { get; set; }  
  14.         public DateTime DOJ { get; set; }  
  15.         public string Department { get; set; }  
  16.         public string Designation { get; set; }  
  17.         public double Salary { get; set; }  
  18.     }  
  19. }  
EmployeeController.cs 
  1. using SampleAPI.Models.Sample;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8. using System.Web.Http.Description;  
  9.   
  10. namespace SampleAPI.Controllers.Sample  
  11. {  
  12.     public class EmployeeController : ApiController  
  13.     {  
  14.         static List<Employee> lstData = new List<Employee>();  
  15.   
  16.         public EmployeeController()  
  17.         {             
  18.         }  
  19.   
  20.         [ResponseType(typeof(Employee))]  
  21.         [HttpGet]  
  22.         [Route("Employee/GetEmployee")]  
  23.         public IHttpActionResult GetEmployee()  
  24.         {  
  25.             if (lstData.Count == 0)  
  26.                 this.FetchEmployee();  
  27.             return Ok(lstData);  
  28.         }  
  29.   
  30.         [ResponseType(typeof(Employee))]  
  31.         [HttpPost]  
  32.         [Route("Employee/AddEmployee")]  
  33.         public IHttpActionResult AddEmployee(Employee objEmp)  
  34.         {  
  35.             return Ok(this.SaveEmployee(objEmp));  
  36.         }  
  37.   
  38.         private List<Employee> FetchEmployee()  
  39.         {  
  40.             Employee objEmp = new Employee() { };  
  41.             objEmp.Id = 1;  
  42.             objEmp.Code = "A001";  
  43.             objEmp.Name = "RABIN";  
  44.             objEmp.DOB = Convert.ToDateTime("10-06-1980");  
  45.             objEmp.DOJ = Convert.ToDateTime("01-09-2006");  
  46.             objEmp.Department = "ACCOUNTS";  
  47.             objEmp.Designation = "CLERK";  
  48.             objEmp.Salary = 15000.00;  
  49.             lstData.Add(objEmp);  
  50.   
  51.             objEmp = new Employee() { };  
  52.             objEmp.Id = 2;  
  53.             objEmp.Code = "A002";  
  54.             objEmp.Name = "SUJIT";  
  55.             objEmp.DOB = Convert.ToDateTime("12-22-1986");  
  56.             objEmp.DOJ = Convert.ToDateTime("04-15-2010");  
  57.             objEmp.Department = "SALES";  
  58.             objEmp.Designation = "MANAGER";  
  59.             objEmp.Salary = 35000.00;  
  60.             lstData.Add(objEmp);  
  61.   
  62.             objEmp = new Employee() { };  
  63.             objEmp.Id = 3;  
  64.             objEmp.Code = "A003";  
  65.             objEmp.Name = "KAMALESH";  
  66.             objEmp.DOB = Convert.ToDateTime("03-22-1982");  
  67.             objEmp.DOJ = Convert.ToDateTime("07-15-2006");  
  68.             objEmp.Department = "ACCOUNTS";  
  69.             objEmp.Designation = "CLERK";  
  70.             objEmp.Salary = 16000.00;  
  71.             lstData.Add(objEmp);  
  72.   
  73.             return lstData;  
  74.         }  
  75.   
  76.         private bool SaveEmployee(Employee objEmp)  
  77.         {  
  78.             objEmp.Id = (lstData.OrderByDescending(s => s.Id).FirstOrDefault()).Id + 1;  
  79.             lstData.Add(objEmp);  
  80.             return true;  
  81.         }  
  82.     }  
  83. }  
Now, run the code and check the output.


Similar Articles