All Categories

HTTP and Observables in Angular2 Constructor

When we need to fetch any data from the server we need to call HTTP Request. Before we will get along with our examples we will understand what is HTTP and observables before accessing to web ?

HTTP Mechanism

Whenever  you have requirement to provide a request from client to the server, We need  http which is used to fetch the data from the server and post the data to the server. HTTP stands for hypertext transfer protocol.


A separate module is assigned to make the HTTP request and fetch the data from the server. It’s the primary protocol for browser/server communication.
First we will, configure the application to use server communication facilities.
@angular/http module. (module which helps us to communicate with the server).
The Angular Http client communicates with the server using a familiar HTTP request/response protocol. The Http client is one of a family of services in the Angular HTTP library.
Before we move forward let us follow the steps which will be required for creating the application using HTTP concept in Angular 2.


An Observable is a stream of events that you can process with array-like operators.Observables are a powerful way to manage asynchronous data flows. Angular core has basic support for observables.
Developers augment that support with operators and extensions from the RxJS library. You’ll see how shortly.

1.You need to know what is Service and Dependency Injection before proceeding to Angular HTTP.
Steps to Fetch data using HTTP

  1. We need to import HttpModule  from the ‘@angular/http’  
  2. We need to declare in @NgModule({

 Imports: [BrowserModule,HttpModule]

3. So by  importing  the HttpModule we are also registering the Http service in Angular Injector.
4.So there is no need to explicitly  register the service like we previously do that it  in Angular 2.2 providers which we defined that @Component decorator of app.component.ts .

In the above image we have explicitly registering the service like in this above image EmployeeService in app.component.ts .
Notes : HttpModule will register the Http service internally.
Here in our example we will be discussing on creating a project and we will understand how to fetch the data using HTTP module of Angular
2.To create a Student Data System we need to write in our cmd :

  • mkdir  StudentSystem
  • cd  StudentSystem
  • ng  new StudentData(command of Angular CLI command line interpreter tool which will install all the dependencies files to create an initial project setup for you.
  • After the installation successful we are done !.

ng serve and run that in localhost:4200

Now Let’s create a StudentService.ts file in our app folder. Which will make the http call from StudentService.ts

Explanation :In this StudentService.service.ts file we have imported Injectable Component from ‘@angular/core’ . We have created
StudentService class which contains getStudent() method with a list of hardcoded Jsondata’s .

constructor(private _http:Http)
//Inside the constructor we are injecting the dependencies of Http.

So we have to import http module in our service.ts file
import {Http} from ‘@angular/http’;
So,  now we have a local variable inside constructor called _http which will refer the instance as  Http.
Now we can fetch the data using http.
So we have got some hard coded json data which we don’t want it anymore, instead we need to use get() method of http to fetch the data by using url. Let me show you. View the below image of our code.

We all still the beginners of this great Front end framework Angular , so let’s not take trouble of creating a web server and configuring it just to serve 4 lines of data.
ate inside app folder in our application folder structure.

List of json data from StudentData.json file.
Now, this contains the required data for our application and we are going to be serving our data from this file than our server.
Let’s go back to StudentService.service.ts file
Create a new variable as :
private _url:string=”APIdata/StudentData.json”;

APIdata is our folder name and StudentData.json is our file name from where will fetch our data.

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
export class StudentService{
private _url:string="APIdata/StudentData.json";
    constructor(private _http:Http)
          return this._http.get(this._url);//url is the String variable which contains the Json data .
//http is a local variable which refers the instance
//of Http. We will invoke get() method

Now we are making get request from the url this._http.get(this._url);
And in future if you do have  a working server just point or replace this url below _url:string=”APIdata/StudentData.json”;
Everything will work as it is .
So that is our first step let’s move to 2nd step.

2.Receive the Observables and map it.
Every Observables got an operators that we can use.

.map(()) ; is an operator and this takes an arrow function as its  argument.
Next step is we should import Response and map operator.

Basically what we are doing is we have received the observables and we have to convert that into json format.  We received  Response object .
We have created a local variable as response and we are converting that into json format response.json());
response<——-   //input

  1. Subscribe to the Observables  and assign the Student Data to local variable in view

We will use also Rxjs Reactive Extension javascript. Externally library to work with Observables.
Now  let create our StudentList component .

Let’s write down code in Student-List.component.ts

Now if we write as ;

Student is a local variable but we can’t directly call getStudent(); here  because we need to subscribe to the observable otherwise we receive the data into the component.
The subscribe() method takes an arrow function as an argument.
now now let’s just write this as :
subscribe(resStudentData => this.Student=resStudentData)
We have a instance of StudentService and with that we are going to call the getStudent() method.
Now if we observe getStudent() it returns an observables as  (method) StudentService.getStudent(): Observable<any>

Observables don’t send data unless you subscribe to them. So StudentService will not send data to Student List unless we subscribe to them.
So on getStudent() //which is an observables we are going to call subscribe. Subscribe method take arrow function as its argument. As the input it is going to take
resStudentData -((parameter) resStudentData: any )  
resStudentData is a parameter res means response and StudentData is the json data from APIdata folder. We are going to assign that to Array of Student is the

Student we have in the view as well and we will iterate over the object to bind the list of names from Student list.

Now Let’s create Student Details Component folder in the app folder and copy the same which we have written in the Student list component.


We are binding our output in Student-details works
With Student id and Student name and gender fetched from the service.


  1. We have included http module in our app.module.ts file. 
  2. We included http as dependency in  StudentService.ts file 

3. We invoke the getmethod passing the url where the request has been made.
Url is nothing but the file which is  APIdata/StudentData.Json
When we make a http call we get Observables but that not a desired format we want json format . map operator on an observables to convert its response into JSON format .
Now from our service we are returning an Observables in json format , but observables doesn’t send out data unless someone Subscribe it to.

  1. Included Subscribe method in Student-list.Component.ts
  2. So when we subscribe to getStudent() we receive the data as a response. So resStudentData is nothing but the observables values in the json format. With that value we are going to assign to our local variable as we see in our local variable is Student[] and this
  3. Student is used in the view to list our all Student names. And the same thing with Student details.

Enroll for the Front-end Web Development Training Course conducted by Acadgild and become a successful Web developer.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles