Angular 2 Http get() Example
April 13, 2017
On this page we will provide angular 2 Http get() example. Angular HTTP library provides Http client for server communication.
get()
is the Http client method that uses HTTP GET method to communicate server using HTTP URL. We need to pass HTTP URL to Http.get()
and it will return the instance of RxJS Observable
. To listen values of Observable
we need to subscribe it. We can also directly fetch Observable
value in our HTML template using async
pipe. Observable
can be converted into Promise
using RxJS toPromise()
method. Http.get()
communicates to server only when we fetch values from Observable
or Promise
. On this page we will create a book service in which we will access books from a URL in JSON format. We will iterate the book using Observable
and Promise
. Find the complete example step by step.
Contents
Software Used
Find the software used in our example.1. Angular 4.0.0
2. TypeScript 2.2.0
3. Node.js 6.10.1
4. Angular CLI 1.0.0
5. Angular Compiler CLI 4.0.0
Http.get()
Http.get()
performs a request with HTTP GET method. The syntax is as given below.
get(url: string, options?: RequestOptionsArgs) : Observable<Response>
get()
is the method of angular Http
API that interacts with server using HTTP GET method. It accepts a HTTP URL and returns Observable
instance. RequestOptionsArgs
is optional. To use HTTP get()
, we need to follow below steps.
Step-1:: First step is that we need to import
HttpModule
in @NgModule
using imports
metadata in our application module.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; @NgModule({ --------- --------- imports: [ BrowserModule, HttpModule ] --------- --------- })
Http
as given below.
constructor(private http:Http) { }
http.get()
.
Observable<Response> ob = this.http.get(this.url);
http.get()
returns instance of Observable
that can be later subscribed to get result. We can also fetch Observable
directly in HTML template using async
pipe.
Observable and Promise
We can use eitherObservable
or Promise
with http.get()
.
Observable: This is a RxJS API.
Observable
is a representation of any set of values over any amount of time. All angular Http
methods return Observable
. Observable
provides methods such as map()
, catch()
etc. map()
applies a function to each value emitted by source Observable
and returns finally an instance of Observable
. catch()
is called when an error is occurred. catch()
also returns Observable
.
Promise: This is a JavaScript class.
Promise
is used for asynchronous computation. A Promise
represents value which may be available now, in the future or never. Promise
is a proxy for a value which is not known when the promise is created. Promise
has methods such as then()
, catch()
etc. http.get()
returns Observable
and to convert it into Promise
we need to call RxJS toPromise()
on the instance of Observable
. The then()
method of Promise
returns a Promise
and that can be chained later. The catch()
method of Promise
is executed when an error is occurred and it also returns Promise
.
Http.get with Observable
Http.get()
returns instance of Observable<Response>
. To change it into instance of Observable<Book[]>
, we need to use RxJS map()
operator.
getBooksWithObservable(): Observable<Book[]> { return this.http.get(this.url) .map(this.extractData) .catch(this.handleErrorObservable); }
extractData()
method. map()
converts Response
object of http.get
into Book
.
private extractData(res: Response) { let body = res.json(); return body; }
http.get
provides catch()
method. Find the handleErrorObservable()
method.
private handleErrorObservable (error: Response | any) { console.error(error.message || error); return Observable.throw(error.message || error); }
Observable
in our HTML template we can go by two way.
1. Angular directive can directly use
Observable
with async
pipe. Find the code snippet that we will write in component.
observableBooks: Observable<Book[]> this.observableBooks = this.bookService.getBooksWithObservable();
observableBooks
with ngFor
as follows.
<ul> <li *ngFor="let book of observableBooks | async" > Id: {{book.id}}, Name: {{book.name}} </li> </ul>
async
pipe will mark observableBooks
to listen for any changes.
2. Subscribe to the
Observable
and fetch values stored by it. Find the code snippet that we will write in component.
observableBooks: Observable<Book[]> books: Book[]; this.observableBooks = this.bookService.getBooksWithObservable(); this.observableBooks.subscribe( books => this.books = books, error => this.errorMessage = <any>error);
books
with ngFor
as follows.
<ul> <li *ngFor="let book of books" > Id: {{book.id}}, Name: {{book.name}} </li> </ul>
Http.get with Promise
Now find the code to useHttp.get
with Promise
.
getBooksWithPromise(): Promise<Book[]> { return this.http.get(this.url).toPromise() .then(this.extractData) .catch(this.handleErrorPromise); }
http.get()
that returns Observable<Response>
. Now on this value we call RxJS toPromise()
method that will convert it into Promise<Response>
. After calling then()
method on it, it returns Promise<Book[]>
. If there is any error then the catch()
method will execute. extractData()
used in then()
, is the same used in map()
method with Observable
. Find the handleErrorPromise()
method used in catch()
.
private handleErrorPromise (error: Response | any) { console.error(error.message || error); return Promise.reject(error.message || error); }
Promise
on our HTML template we can go by two way.
1. Get instance of
Promise
and use it in HTML template with async
pipe. Find the code snippet that we will write in component.
promiseBooks: Promise<Book[]> this.promiseBooks = this.bookService.getBooksWithPromise();
promiseBooks
in our HTML template using ngFor
with async
pipe as follows.
<ul> <li *ngFor="let book of promiseBooks | async" > Id: {{book.id}}, Name: {{book.name}} </li> </ul>
then()
method and assign value to our component variable as follows.
promiseBooks: Promise<Book[]> books: Book[]; this.promiseBooks = this.bookService.getBooksWithPromise(); this.promiseBooks.then( books => this.books = books, error => this.errorMessage = <any>error);
books
in HTML template using ngFor
as follows.
<ul> <li *ngFor="let book of books" > Id: {{book.id}}, Name: {{book.name}} </li> </ul>
Complete Example
Now find the complete example.book.service.ts
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/toPromise'; import { Book } from './book'; @Injectable() export class BookService { url = "http://localhost:4200/assets/data/books.json"; constructor(private http:Http) { } getBooksWithObservable(): Observable<Book[]> { return this.http.get(this.url) .map(this.extractData) .catch(this.handleErrorObservable); } getBooksWithPromise(): Promise<Book[]> { return this.http.get(this.url).toPromise() .then(this.extractData) .catch(this.handleErrorPromise); } private extractData(res: Response) { let body = res.json(); return body; } private handleErrorObservable (error: Response | any) { console.error(error.message || error); return Observable.throw(error.message || error); } private handleErrorPromise (error: Response | any) { console.error(error.message || error); return Promise.reject(error.message || error); } }
export class Book { id: number; name: string; constructor() { } }
[ {"id": 1, "name": "Core Java"}, {"id": 2, "name": "Angular 2"}, {"id": 3, "name": "Hibernate"} ]
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { BookService } from './book.service'; import { Book } from './book'; @Component({ selector: 'app-observable', templateUrl: './observable.component.html' }) export class ObservableComponent implements OnInit { observableBooks: Observable<Book[]> books: Book[]; errorMessage: String; constructor(private bookService: BookService) { } ngOnInit(): void { this.observableBooks = this.bookService.getBooksWithObservable(); this.observableBooks.subscribe( books => this.books = books, error => this.errorMessage = <any>error); } }
<h3>Book Details with Observable</h3> <ul> <li *ngFor="let book of observableBooks | async" > Id: {{book.id}}, Name: {{book.name}} </li> </ul> <h3>Book Details after "subscribe" to Observable </h3> <ul> <li *ngFor="let book of books" > Id: {{book.id}}, Name: {{book.name}} </li> </ul> <div *ngIf="errorMessage"> {{errorMessage}} </div>
import { Component, OnInit } from '@angular/core'; import { BookService } from './book.service'; import { Book } from './book'; @Component({ selector: 'app-promise', templateUrl: './promise.component.html' }) export class PromiseComponent implements OnInit { promiseBooks: Promise<Book[]> books: Book[]; errorMessage: String; constructor(private bookService: BookService) { } ngOnInit(): void { this.promiseBooks = this.bookService.getBooksWithPromise(); this.promiseBooks.then( books => this.books = books, error => this.errorMessage = <any>error); } }
<h3>Book Details with Promise</h3> <ul> <li *ngFor="let book of promiseBooks | async" > Id: {{book.id}}, Name: {{book.name}} </li> </ul> <h3>Book Details after "then" to Promise </h3> <ul> <li *ngFor="let book of books" > Id: {{book.id}}, Name: {{book.name}} </li> </ul> <div *ngIf="errorMessage"> {{errorMessage}} </div>
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <app-observable></app-observable> <app-promise></app-promise> ` }) export class AppComponent { }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { ObservableComponent } from './observable.component'; import { PromiseComponent } from './promise.component'; import { BookService } from './book.service'; @NgModule({ imports: [ BrowserModule, HttpModule ], declarations: [ AppComponent, ObservableComponent, PromiseComponent ], providers: [ BookService ], bootstrap: [ AppComponent ] }) export class AppModule { }
Test Application
To test the application, find following steps.1.: Download source code. In angular CLI application, place src folder.
2. Inside src/assets/data folder we have placed
books.json
file. We can access JSON data using following URL.
http://localhost:4200/assets/data/books.json

To use parameters with
Http.get()
, find the link.
Angular 2 Http get() Parameters + Headers + URLSearchParams + RequestOptions Example
Note: Angular version 4.3 has introduced
HttpClient
to perform HTTP requests. If we are using Angular version 4.3 or higher, we should use HttpClient
. Find the example to handle GET
request using HttpClient
.
Angular HttpClient get Example