Learn Angular 4.0 In 10 Days - AJAX Request Handling - Day Eight

Let us start day 8 of the "Learning Angular 4.0 in 10 Days" series. In the previous articles, we discussed dependency injection and the concept of service in Angular 4.0. If you want to read the previous articles of this series, do visit the below links.

Angular 4.0 introduces many innovative concepts like performance improvements, the Component Routing, sharpened Dependency Injection (DI), lazy loading, async templating, mobile development with Native Script; all linked with a solid tooling and excellent testing support. Making HTTP requests in Angular 4.0 apps looks somewhat different than what we're used to from Angular 1.x, a key difference being that Angular 4's Http returns observables.

It is very clear to us that Angular 4.0 always looks and feels different than the Angular 1.x. In the case of HTTP API calls, the same scenario occurs. The $HTTP service which Angular 1.x provides us works very nicely in most cases. Angular 4.0 HTTP requires that we need to learn some new concept or mechanism, including how to work with observables.

Reactive Extensions for JavaScript (RxJS) is a reactive streams library that allows you to work with Observables. RxJS combines Observables, Operators, and Schedulers so we can subscribe to streams and react to changes using composable operations.

Differences between Angular 1.x $http and Angular 2 Http

Angular 4's HTTP API calling again provides a fairly straightforward way of handling requests. For starters, HTTP calls in Angular 4 by default return observables through RxJS, whereas $http in Angular 1.x returns promises. Using observable streams gives us the benefit of greater flexibility when it comes to handling the responses coming from HTTP requests. For example, we have the potential of tapping into useful RxJS operators like retry so that a failed HTTP request is automatically re-sent, which is useful for cases where users have poor or intermittent network communication.

In Angular 4, HTTP is accessed as an injectable class from angular4/HTTP and, just like other classes, we import it when we want to use it in our components. Angular 4 also comes with a set of injectable providers for HTTP, which are imported via HTTP_PROVIDERS. With these, we get providers such as RequestOptions and response options, which allow us to modify requests and responses by extending the base class for each. In Angular 1.x, we would do this by providing a transformRequest or transformResponse function to our $httpoptions.

Observables vs Promises

When used with HTTP, both implementations provide an easy API for handling requests, but there are some key differences that make Observables a superior alternative,

  • Promises only accept one value unless we compose multiple promises (Eg: $q.all).
  • Promises can’t be canceled.

We already discussed that in Angular 4.0, there are many new features introduced in Angular 4.0. An exciting new feature used with Angular is the 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 data. Angular uses observables extensively - you'll see them in the HTTP service and the event system.

In version 4.0, Angular mainly introduces reactive programming concepts based on the observables for dealing with the asynchronous processing of data. In angular 1.x, we basically used promises to handle the asynchronous processing. But still, in Angular 4.0, we can still use the promises for the same purpose. The main concept of reactive programming is the observable element which related to the entity that can be observed. Basically, at a 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 to details example of observables, first, we need to understand how to define an observables objects. To create an observable, we can use the create method of the Observable object. A function must be provided as a 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.     setTimeout(() => {  
  3.         observer.next('some event');  
  4.     }, 500);  
  5. });  


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

  • next – Emit an event. This can be called several times.
  • 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.
  • 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. In spite 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 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 trigger 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 canceled. 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.
Observables vs Promises

Both Promises and Observables provide us with abstractions that help us 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 access to the original function that returned the promise in order to have a retry capability.

Observable HTTP Events

A common operation in any web application is getting or posting data to a server. Angular applications do this with the Http library, which previously used Promises to operate in an asynchronous manner. The updated Http library now incorporates Observables for triggering 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 much 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?

  1. map will create a new array with the results of calling a provided function on every element in this array. In the below example 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.

  2. filter will create a new array with all 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 salaries.

Note, the chaining function style and the optional static typing that comes with TypeScript, that we used in this example. Most important functions like filter return an Observable, as in Observables beget other Observables, similarly 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.

The Angular 4 HTTP module @angular/http exposes an HTTP service that our application can use to access web services over HTTP. We’ll use this utility in our PeopleService service. We start by importing it together will all types involved in doing an HTTP request:

  1. import { Http, Response } from '@angular/http';
  2. import { Observable } from 'rxjs/Rx';

These are all types and method required to make and handle an HTTP request to a web service:


The Angular 4 HTTP service that provides the API to make HTTP requests with methods corresponding to HTTP verbs like getting, post, put, etc


Represents a response from an HTTP service and follows the fetch API specification

Observable is the async pattern used in Angular 4. The concept of observable comes from the observer design pattern as an object that notifies an interested party of observers when something interesting happens. In RxJs it has been generalized to manage sequences of data or events, to become composable with other observables and to provide a lot of utility functions known as operators that let you achieve amazing stuff.

Angular comes with its own HTTP library which we can use to call out to external APIs.

When we make calls to an external server, we want our user to continue to be able to interact with the page. That is, we don’t want our page to freeze until the HTTP request returns from the external server. To achieve this effect, our HTTP requests are asynchronous.

Dealing with asynchronous code is, historically, more tricky than dealing with synchronous code. In Javascript, there are generally three approaches to dealing with async code:

  1. Callbacks
  2. Promises
  3. Observables
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 following requests.

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

The http.post signature above reads as follows. We need to provide a URL and 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 a map to extract the JSON object from the response and subscribe. This will set up our stream as soon as it emits the result.

Differences between $http and angular/http

Angular 4 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 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.

Sample Code of app.component.employeelist.ts

Try to solve the new Formula Cube! It works exactly like a Rubik's Cube but it is only $2, from China. Learn to solve it with the tutorial on rubiksplace.com or use the solver to calculate the solution in a few steps. (Please subscribe for a membership to stop adding promotional messages to the documents)

  1. import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';  
  2. import { Http, Response } from '@angular/http';  
  3. import 'rxjs/Rx';  
  5. @Component({  
  6.     moduleId: module.id,  
  7.     selector: 'employee-list',  
  8.     templateUrl: 'app.component.employeelist.html'  
  9. })  
  11. export class EmployeeListComponent implements OnInit {  
  13.     private data: Array<any> = [];  
  14.     private showDetails: boolean = true;  
  15.     private showEmployee: boolean = false;  
  17.     constructor(private http: Http) {  
  18.     }  
  20.     ngOnInit(): void {  
  22.     }  
  24.     ngAfterViewInit(): void {  
  25.         this.loadData();  
  26.     }  
  28.     private loadData(): void {  
  29.         let self = this;  
  30.         this.http.request('http://localhost:4501/employee/getemployee')  
  31.             .subscribe((res: Response) => {  
  32.                 self.data = res.json();  
  33.             });  
  34.     }  
  36.     private addEmployee(): void {  
  37.         this.showDetails = false;  
  38.         this.showEmployee = true;  
  39.     }  
  41.     private onHide(args: boolean): void {  
  42.         this.showDetails = !args;  
  43.         this.showEmployee = args;  
  44.         this.loadData();  
  45.     }  
  46. }  
Sample Code of app.component.employeelist.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>   
Sample Code of app.component.employeeadd.ts 
  1. import { Component, OnInit, EventEmitter, Output } from '@angular/core';  
  2. import { Http, Response, Headers } from '@angular/http';  
  3. import 'rxjs/Rx';  
  5. @Component({  
  6.     moduleId: module.id,  
  7.     selector: 'employee-add',  
  8.     templateUrl: 'app.component.employeeadd.html'  
  9. })  
  11. export class AddEmployeeComponent implements OnInit {  
  13.     private _model: any = {};  
  14.     @Output() private onHide: EventEmitter<boolean> = new EventEmitter<boolean>();  
  16.     constructor(private http: Http) {  
  17.     }  
  19.     ngOnInit(): void {  
  21.     }  
  23.     private onCancel(): void {  
  24.         this._model = {};  
  25.         this.onHide.emit(false);  
  26.     }  
  28.     private submit(): void {  
  29.         debugger;  
  30.         if (this.validate()) {  
  31.             let self = this;  
  32.             let headers = new Headers();  
  33.             headers.append('Content-Type''application/json; charset=utf-8');  
  34.             this.http.post("http://localhost:4501/employee/AddEmployee"this._model, { headers: headers })  
  35.                 .subscribe((res: Response) => {  
  36.                     self.onCancel();  
  37.                 });  
  39.         }  
  40.     }  
  42.     private reset(): void {  
  43.         this._model = {};  
  44.     }  
  46.     private validate(): boolean {  
  47.         let status: boolean = true;  
  48.         if (typeof (this._model.code) === "undefined") {  
  49.             alert('Alias is Blank');  
  50.             status = false;  
  51.             return;  
  52.         }  
  53.         else if (typeof (this._model.name) === "undefined") {  
  54.             alert('Name is Blank');  
  55.             status = false;  
  56.             return;  
  57.         }  
  58.         else if (typeof (this._model.dob) === "undefined") {  
  59.             alert('dob is Blank');  
  60.             status = false;  
  61.             return;  
  62.         }  
  63.         else if (typeof (this._model.doj) === "undefined") {  
  64.             alert('DOJ is Blank');  
  65.             status = false;  
  66.             return;  
  67.         }  
  68.         else if (typeof (this._model.department) === "undefined") {  
  69.             alert('Department is Blank');  
  70.             status = false;  
  71.             return;  
  72.         }  
  73.         else if (typeof (this._model.designation) === "undefined") {  
  74.             alert('Designation is Blank');  
  75.             status = false;  
  76.             return;  
  77.         }  
  78.         else if (typeof (this._model.salary) === "undefined") {  
  79.             alert('Salary is Blank');  
  80.             status = false;  
  81.             return;  
  82.         }  
  83.         return status;  
  84.     }  
  85. }  
Sample Code of app.component.employeeadd.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()" />  
  37.                 <input type="button" value="Cancel" (click)="onCancel()" />  
  38.             </td>  
  39.         </tr>  
  40.     </table>  
  41. </div>  
Now for accessing http requests in the above example, we create a Employee Web API Controller which will store and add employee data and return the existing employee list. Sample Code is as below,
Sample code of EmployeeController
  1. using Angular4_Models;  
  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;  
  10. namespace Angular4_API.Controllers  
  11. {  
  12.     public class EmployeeController : ApiController  
  13.     {  
  14.         public static List<Employee> lstData = new List<Employee>();  
  16.         public EmployeeController()  
  17.         {  
  18.             if (lstData.Count == 0)  
  19.                 this.FetchEmployee();  
  20.         }  
  22.         [ResponseType(typeof(Employee))]  
  23.         [HttpGet]  
  24.         [Route("Employee/GetEmployee")]  
  25.         public IHttpActionResult GetEmployee()  
  26.         {  
  27.             if (lstData.Count == 0)  
  28.                 this.FetchEmployee();  
  29.             return Ok(lstData);  
  30.         }  
  32.         [ResponseType(typeof(Employee))]  
  33.         [HttpPost]  
  34.         [Route("Employee/AddEmployee")]  
  35.         public IHttpActionResult AddEmployee(Employee objEmp)  
  36.         {  
  37.             return Ok(this.SaveEmployee(objEmp));  
  38.         }  
  40.         private List<Employee> FetchEmployee()  
  41.         {  
  42.             Employee objEmp = new Employee() { };  
  43.             objEmp.Id = 1;  
  44.             objEmp.Code = "A001";  
  45.             objEmp.Name = "RABIN";  
  46.             objEmp.DOB = Convert.ToDateTime("10-06-1980");  
  47.             objEmp.DOJ = Convert.ToDateTime("01-09-2006");  
  48.             objEmp.Department = "ACCOUNTS";  
  49.             objEmp.Designation = "CLERK";  
  50.             objEmp.Salary = 15000.00;  
  51.             lstData.Add(objEmp);  
  53.             objEmp = new Employee() { };  
  54.             objEmp.Id = 2;  
  55.             objEmp.Code = "A002";  
  56.             objEmp.Name = "SUJIT";  
  57.             objEmp.DOB = Convert.ToDateTime("22-12-1986");  
  58.             objEmp.DOJ = Convert.ToDateTime("04-10-2010");  
  59.             objEmp.Department = "SALES";  
  60.             objEmp.Designation = "MANAGER";  
  61.             objEmp.Salary = 35000.00;  
  62.             lstData.Add(objEmp);  
  64.             objEmp = new Employee() { };  
  65.             objEmp.Id = 3;  
  66.             objEmp.Code = "A003";  
  67.             objEmp.Name = "KAMALESH";  
  68.             objEmp.DOB = Convert.ToDateTime("03-06-1982");  
  69.             objEmp.DOJ = Convert.ToDateTime("07-05-2006");  
  70.             objEmp.Department = "ACCOUNTS";  
  71.             objEmp.Designation = "CLERK";  
  72.             objEmp.Salary = 16000.00;  
  73.             lstData.Add(objEmp);  
  75.             return lstData;  
  76.         }  
  78.         private bool SaveEmployee(Employee objEmp)  
  79.         {  
  80.             objEmp.Id = (lstData.OrderByDescending(s => s.Id).FirstOrDefault()).Id + 1;  
  81.             lstData.Add(objEmp);  
  82.             return true;  
  83.         }  
  84.     }  
  85. }  
Sample Code of Employee Model Class
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  6. namespace Angular4_Models  
  7. {  
  8.     public class Employee  
  9.     {  
  10.         public int Id { getset; }  
  11.         public string Code { getset; }  
  12.         public string Name { getset; }  
  13.         public DateTime DOB { getset; }  
  14.         public DateTime DOJ { getset; }  
  15.         public string Department { getset; }  
  16.         public string Designation { getset; }  
  17.         public double Salary { getset; }  
  18.     }  
  19. }  
Sample code of WebApi.config for the Web API Controller (Employee Controller)
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!--  
  3.   For more information on how to configure your ASP.NET application, please visit  
  4.   http://go.microsoft.com/fwlink/?LinkId=301879  
  5.   -->  
  6. <configuration>  
  7.   <appSettings></appSettings>  
  8.   <system.web>  
  9.     <compilation debug="true" targetFramework="4.5.2" />  
  10.     <httpRuntime targetFramework="4.5.2" />  
  11.   </system.web>  
  12.   <system.webServer>  
  13.   <handlers>  
  14.       <remove name="ExtensionlessUrlHandler-Integrated-4.0" />  
  15.       <remove name="OPTIONSVerbHandler" />  
  16.       <remove name="TRACEVerbHandler" />  
  17.       <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />  
  18.     </handlers></system.webServer>  
  19.   <runtime>  
  20.     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
  21.       <dependentAssembly>  
  22.         <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />  
  23.         <bindingRedirect oldVersion="" newVersion="" />  
  24.       </dependentAssembly>  
  25.       <dependentAssembly>  
  26.         <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />  
  27.         <bindingRedirect oldVersion="" newVersion="" />  
  28.       </dependentAssembly>  
  29.       <dependentAssembly>  
  30.         <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />  
  31.         <bindingRedirect oldVersion="" newVersion="" />  
  32.       </dependentAssembly>  
  33.       <dependentAssembly>  
  34.         <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />  
  35.         <bindingRedirect oldVersion="" newVersion="" />  
  36.       </dependentAssembly>  
  37.       <dependentAssembly>  
  38.         <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />  
  39.         <bindingRedirect oldVersion="" newVersion="" />  
  40.       </dependentAssembly>  
  41.       <dependentAssembly>  
  42.         <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />  
  43.         <bindingRedirect oldVersion="" newVersion="" />  
  44.       </dependentAssembly>  
  45.     </assemblyBinding>  
  46.   </runtime>  
  47.   <system.codedom>  
  48.     <compilers>  
  49.       <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />  
  50.       <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />  
  51.     </compilers>  
  52.   </system.codedom>  
  53. </configuration>  
Now the Output of the above code is as below:
Screen 1 

Screen 2

Screen 3


<< Read Part 7 of this article here