Consuming real data using the http service in angular 2


Today in the series Learning angular 2 step by step, we will learn Consuming real Data from a web service using the HTTP service in angular 2.

You might be thinking that what is HTTP Service?

Just like in Angular 1.x, Angular 2 also provides Http service for making requests to the server.

Before reading this article, I would recommend reading my previous tutorial where I have explained about Angular 2 Component.

Till now In this series "Learn angular 2 step by step", we have learned Setup angular 2 application, we learned about Angular 2 components, Nested component, Angular 2 directives and also we have seen how to setup basic routing in angular 2. But we have not made any HTTP request to the server which is a one of the most important operation in any front-end applications. Right?

Let's learn to make HTTP request in an angular 2 application. 

Here in this tutorial, we will see how to retrieve data from a web service using the http module in Angular 2.

Let's start setup basic routing in our angular 2 application. 

So, I will open the Application in VS Code Editor what we have created in the previous tutorial. Download the application if you want.

Create an Angular2 service.

Here in this application, we will create a service class first, where we will write code for making an HTTP request to a server.

Now the question is, what is service in Angular 2 & why we will use services?

In Angular, a service is basically any set of common functionality, needs to be provided to various components. example. we can create a service class with web service API call functionality that could be reused among various components.

So using services, we can increase reusability of our code. right?

Let's create a service class in angular 2 first.

Here in our application, I will create another folder inside this app folder for creating the service class So, Right click on the app folder > New Folder > enter folder name > "Services" and then I will add a new file in this service folder for create the service class. Right-click on the folder > New file > enter file name "employee.service.ts".

import { Injectable} from '@angular/core'
import {Http} from '@angular/http'
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/operator/map'
import {EmployeeModel} from '../Models/EmployeeModel'

export class EmployeeService{
    constructor(private http: Http){

        return this.http.get('')
            .map((res: any)=> res.json() as EmployeeModel[]);

You can see in the above service class file I have imported Injectable decorator from '@angular/core', this is required to make the service class injectable. This allows the functionality of this class to be injected and used in any Angular JS components.

I have also imported the HTTP from '@angular/http', this is required to use the HTTP service to access web services over HTTP.

I have imported Observable from rxjs library - We need this Observable because in angular2 the HTTP service returns Observable with the Response object, wherein angular 1.x the Http service returns Promises.
Observables are the recommended way for dealing with data in Angular 2 because there are some great features like 1. Observables may emit data more than once, they are cancellable means we can cancel the result of an HTTP request if the request isn't needed anymore and more. We will see in more details about the Observables in next videos. Ok.

Then I have imported map operator from rxjs library also, we need this to convert the response data coming from the web service to JSON data.

Here the function GetEmployee is a blueprint for making HTTP requests. Nothing will happen until we call subscribe() method.

Create an angular2 component. 

Now in our application, I will create a new angular2 Component where we will use the service for fetching remote data from web service and display in the component.

we can used the employeelist component what we had created in the second part of this series learning angular 2 step by step but I have created a new component for making this example clean and easy to understand. Ok.

So for creating the new component, I will add an another folder here inside the app folder for the component. So right-click on the app folder > New Folder > Enter folder name > "EmployeeListRemote"

Now in this folder, we will add a new typescript file for creating the angular 2 component where we will use the service for fetching data from remote server.

So right click on the folder > New File > enter file name, here I will enter "employee-list-remote.component.ts"

import{Component, OnInit} from '@angular/core'
import {EmployeeService} from '../Services/employee.service'
import {EmployeeModel} from '../Models/EmployeeModel'

    selector: 'employee-list-remote',
    templateUrl: 'employee-list-remote-component.html',
export class EmployeeListRemoteComponent implements OnInit{
    public EmployeeList : Array<EmployeeModel> = [];
    constructor(private service: EmployeeService){

            data => {this.EmployeeList = data;},
            error => {alert('Error!');}

You can see here I have imported the EmployeeService for fetching data from remote server. I have also imported the OnInit from '@angular/core', as we will load the data after just load the component, we will implement OnInit as this is the recommended way to load initial data.

In the ngOnInit method, we have called the GetEmployee function from the service and called the subsribe method for getting JSON data from remote server.

Create the template file. 

In the EmployeeListRemote Component, we have defined "employee-list-remote-component.html" as templateUrl, So let's create the template file.

Here in the "EmployeeListRemote" folder we will create the HTML file, So adding  the HTML file right-click on the EmployeeListRemote folder inside app folder >  New File > Enter file name "employee-list-remote-component.html". Write the below HTML Code.

<h2>Employee List from remote server</h2>
<table class="table table-responsive table-bordered table-striped">
            <th>Employee ID</th>
            <th>Contact No</th>
        <tr *ngFor="let item of EmployeeList">
            <td>{{item.FirstName}} {{item.LastName}}</td>

Update app.module.ts 

Here in our bootstrap Module, we will import 3 things. The EmployeeListRemote Component, the service what we have created for fetch employee data from remote server and the HTTPModule. This HttpModule is required as we have used HTTP provider in our service class.

import { NgModule } from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {AppComponent} from "./app.component"
import {EmployeeListComponent} from './EmployeeList/employee-list.component'
import {SearchbarComponent} from './Shared/SearchBar/searchbar.component'
import {MyVisibilityDirective} from './Shared/MyVisibility/myvisibility.directive'
import {RangeRepeaterDirective} from './Shared/RangeRepeater/range-repeater.directive'

import {DashboardComponent} from './Dashboard/dashboard.component'
import {MyAppRoutes} from './app.routes'
import {RouterModule} from '@angular/router'

import {PageNotFoundComponent} from './PageNotFound/page-not-found.component'
import {EmployeeDetailsComponent} from './EmployeeList/employee-details.component'

import {HttpModule} from '@angular/http'
import {EmployeeService} from './Services/employee.service'
import {EmployeeListRemoteComponent} from './EmployeeListRemote/employee-list-remote.component'
    imports: [BrowserModule, RouterModule.forRoot(MyAppRoutes) ,HttpModule],
    declarations: [AppComponent,EmployeeListComponent, SearchbarComponent,
    MyVisibilityDirective, RangeRepeaterDirective, DashboardComponent, 
    PageNotFoundComponent, EmployeeDetailsComponent, EmployeeListRemoteComponent],
    providers: [EmployeeService]
export class AppModule{


You can see that line 10-20 we have imported the HttpModule, EmployeeService and EmployeeListRemoteComponent. also you can notice that in line  I have updated our bootstrap component to EmployeeListRemoteComponent for showing that module on our index.html page. 

Update index.html page

As I have changed the root component to EmployeeListRemoteComponent, I have to update our index.html page also.

<!DOCTYPE html>
        <base href="/">
        <title>This is my frist angular 2 app</title>
        <meta charset="utf-8"/>

        <link rel="stylesheet" type="text/css" href="">
        <link rel="stylesheet" href="./assets/mycss.css">
        <!-- 1. Load libraries -->
        <!-- Polyfill(s) for older browsers -->
        <script src="../node_modules/core-js/client/shim.min.js"></script>
        <script src="../node_modules/zone.js/dist/zone.js"></script>
        <script src="../node_modules/reflect-metadata/Reflect.js"></script>
        <script src="../node_modules/systemjs/dist/system.src.js"></script>
        <!-- System.JS configuration -->
        <script src="./Systemjs.config.js"></script>
                "defaultJSExtensions": true


    <body class="container">
        <!--<app>Please Wait...</app>-->
        <!--<div class="row">
            <div class="md-col-12">
                <employee-list>Loading Employee List...</employee-list>

Run Application

For run the application go to View menu > click on Integrated Command > it will open the terminal > write npm start in the terminal and hit the enter key.<
 Live Demo coming soon Download

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms,, sql server, entity framework, Ajax, Jquery, web api, web service and more.