AngularJS 2.0 From The Beginning - Http Module Part Two - Day Eighteen

I am here to continue the discussion around AngularJS 2.0. In my previous article, I have already discussed about the get method of http module and how to fetch data from a Web API in Angular 2.0. Now, in this article, we will discuss about http module or how to call Post method of external APIs in the Angular 2.0. In case you did not have a look at the previous articles of this series, go through the links mentioned below. 

Http Post

Let’s imagine we received the username and password from a form the user submitted. We would call authenticate to log in the user. Once the user is logged in, we will proceed to store the token so we can include it in the following requests.

  1. http.post(url: string, body: string, options?: RequestOptionsArgs) : Observable<Response>  

The http.post signature above reads as follows. We need to provide a URL, a body, both strings, and then optionally an options object. In our example, we are passing the modified headers property. http.post returns an Observable, we use map to extract the JSON object from the response and subscribe. This will setup our stream as soon as it emits the result.

Differences between $http and angular/http

Angular 2 Http by default returns an Observable opposed to a Promise ($q module) in $http. This allows us to use more flexible and powerful RxJS operators, like switchMap (flatMapLatest in version 4), retry, buffer, debounce, merge or zip. By using Observables, we improve the readability and maintenance of our application, as they can respond gracefully to more complex scenarios involving multiple emitted values opposed to only a one-off single value. 

Now, demonstrate the below concept. We first need to develop a Web API with POST method which accepts a model data from UI and stores it in the repository.
 
Now, for this, first we need to create a model class and then create the Controller.
 
Employee.cs (Employee 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. }  
In the Web API Controller, we initially stored three records. And after it, when user fills up the employee form and clicks on Submit button, that particular record will be appened along with these three records.
 
app.component.employee.ts 
  1. import { Component, OnInit, EventEmitter, Output } from '@angular/core';  
  2. import { Http, Response, Headers } from '@angular/http';  
  3. import 'rxjs/Rx';  
  4.   
  5. @Component({  
  6.     moduleId: module.id,  
  7.     selector: 'employee-add',  
  8.     templateUrl: 'app.component.employeeadd.html'  
  9. })  
  10.   
  11. export class AddEmployeeComponent implements OnInit {  
  12.   
  13.     private _model: any = {};  
  14.     @Output() private onHide: EventEmitter<boolean> = new EventEmitter<boolean>();  
  15.   
  16.     constructor(private http: Http) {  
  17.     }  
  18.   
  19.     ngOnInit(): void {  
  20.   
  21.     }  
  22.   
  23.     private onCancel(): void {  
  24.         this._model = {};  
  25.         this.onHide.emit(false);  
  26.     }  
  27.   
  28.     private submit(): void {  
  29.         if (this.validate()) {  
  30.             let self = this;  
  31.             let headers = new Headers();  
  32.             headers.append('Content-Type''application/json');  
  33.             this.http.post("http://localhost:5201/employee/AddEmployee"this._model, { headers: headers })  
  34.                 .subscribe((res: Response) => {  
  35.                     self.onCancel();  
  36.                 });  
  37.               
  38.         }  
  39.     }  
  40.   
  41.     private reset(): void {  
  42.         this._model = {};  
  43.     }  
  44.   
  45.     private validate(): boolean {  
  46.         let status: boolean = true;  
  47.         if (typeof (this._model.code) === "undefined") {  
  48.             alert('Alias is Blank');  
  49.             status = false;  
  50.             return;  
  51.         }  
  52.         else if (typeof (this._model.name) === "undefined") {  
  53.             alert('Name is Blank');  
  54.             status = false;  
  55.             return;  
  56.         }  
  57.         else if (typeof (this._model.dob) === "undefined") {  
  58.             alert('dob is Blank');  
  59.             status = false;  
  60.             return;  
  61.         }  
  62.         else if (typeof (this._model.doj) === "undefined") {  
  63.             alert('DOJ is Blank');  
  64.             status = false;  
  65.             return;  
  66.         }  
  67.         else if (typeof (this._model.department) === "undefined") {  
  68.             alert('Department is Blank');  
  69.             status = false;  
  70.             return;  
  71.         }  
  72.         else if (typeof (this._model.designation) === "undefined") {  
  73.             alert('Designation is Blank');  
  74.             status = false;  
  75.             return;  
  76.         }  
  77.         else if (typeof (this._model.salary) === "undefined") {  
  78.             alert('Salary is Blank');  
  79.             status = false;  
  80.             return;  
  81.         }  
  82.         return status;  
  83.     }  
  84. }  
app.component.employee.html 
  1. <div class="panel panel-default">  
  2.     <h4>Provide Employee Details</h4>  
  3.     <table class="table" style="width:60%;">  
  4.         <tr>  
  5.             <td>Employee Code</td>  
  6.             <td><input type="text" [(ngModel)]="_model.code" /></td>  
  7.         </tr>  
  8.         <tr>  
  9.             <td>Employee Name</td>  
  10.             <td><input type="text" [(ngModel)]="_model.name" /></td>  
  11.         </tr>  
  12.         <tr>  
  13.             <td>Date of Birth</td>  
  14.             <td><input type="date" [(ngModel)]="_model.dob" /></td>  
  15.         </tr>  
  16.         <tr>  
  17.             <td>Date of Join</td>  
  18.             <td><input type="date" [(ngModel)]="_model.doj" /></td>  
  19.         </tr>  
  20.         <tr>  
  21.             <td>Department</td>  
  22.             <td><input type="text" [(ngModel)]="_model.department" /></td>  
  23.         </tr>  
  24.         <tr>  
  25.             <td>Designation</td>  
  26.             <td><input type="text" [(ngModel)]="_model.designation" /></td>  
  27.         </tr>  
  28.         <tr>  
  29.             <td>Salary</td>  
  30.             <td><input type="number" [(ngModel)]="_model.salary" /></td>  
  31.         </tr>  
  32.         <tr>  
  33.             <td></td>  
  34.             <td>  
  35.                 <input type="button" value="Submit" (click)="submit()" />  
  36.                      
  37.                 <input type="button" value="Cancel" (click)="onCancel()" />  
  38.             </td>  
  39.         </tr>  
  40.     </table>  
  41. </div>  
app.component.homepage.ts
  1. import { Component, OnInit, ViewChild, AfterViewInit } 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.     private showDetails: boolean = true;  
  15.     private showEmployee: boolean = false;  
  16.   
  17.     constructor(private http: Http) {  
  18.     }  
  19.   
  20.     ngOnInit(): void {  
  21.   
  22.     }  
  23.   
  24.     ngAfterViewInit(): void {  
  25.         debugger;  
  26.         this.loadData();  
  27.     }  
  28.   
  29.     private loadData(): void {  
  30.         let self = this;  
  31.         this.http.request('http://localhost:5201/employee/getemployee')  
  32.             .subscribe((res: Response) => {  
  33.                 debugger;  
  34.                 self.data = res.json();  
  35.             });  
  36.     }  
  37.   
  38.     private addEmployee(): void {  
  39.         this.showDetails = false;  
  40.         this.showEmployee = true;  
  41.     }  
  42.   
  43.     private onHide(args: boolean): void {  
  44.         this.showDetails = !args;  
  45.         this.showEmployee = args;  
  46.         this.loadData();  
  47.     }  
  48. }   
app.component.homepage.html 
  1. <div>  
  2.     <h3>HTTP Module Sample - Add and Fetch Data</h3>  
  3.     <div class="panel panel-default" *ngIf="showDetails">  
  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)="addEmployee()">  
  33.                     Add Employee  
  34.                 </button>  
  35.             </p>  
  36.         </div>  
  37.     </div>  
  38.     <div class="panel panel-default" *ngIf="showEmployee">          
  39.         <employee-add (onHide)="onHide($event);"></employee-add>  
  40.     </div>  
  41. </div>  
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);  
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 { AddEmployeeComponent } from './src/app.component.employeeadd';  
  8.   
  9. @NgModule({  
  10.     imports: [BrowserModule, FormsModule, HttpModule],  
  11.     declarations: [HomePageComponent, AddEmployeeComponent],  
  12.     bootstrap: [HomePageComponent]  
  13. })  
  14. export class AppModule { }  
index.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Angular2 - HTTP Module (POST & 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>  
Now, run the code in browser and you will see the below result.

 
 
 

Up Next
    Ebook Download
    View all
    Learn
    View all