Angular HTTP GET Example
August 10, 2021
On this page we will provide Angular HTTP GET example. The Angular HttpClient
class performs HTTP requests. The HttpClient
is available as an injectable class. It has methods to perform HTTP requests. Each method has multiple signatures and its return type varies based on the signature. The HttpClient
methods are get()
, post()
, put()
, delete()
, request()
, head()
, jsonp()
, options()
, patch()
. They return Observable
instance.
The
Observable
can be converted into Promise
using RxJS Observable.toPromise()
method. The HttpClient.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
instance and Promise
instance. Find the complete example step by step.
Contents
Technologies Used
Find the technologies being used in our example.1. Angular 12.1.0
2. Node.js 12.14.1
3. NPM 7.20.3
HttpClient.get()
The syntax ofHttpClient.get()
is as following.
get(url, options): Observable<any>
options: This is an object type. This parameter is optional, if not passed, the default values are assigned.
Find the complete attributes of
options
parameter in get()
method.
options: { headers?: HttpHeaders|{[header: string]: string | string[]}, context?: HttpContext, observe?: 'body'|'events'|'response', params?: HttpParams| {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>}, reportProgress?: boolean, responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean }
The return type
Observable<any>
depends on the responseType
. If responseType?: "json"
then it will return Observable<HttpEvent<Object>>
. The responseType
can be json
, text
, blob
and arraybuffer
.
To use HttpClient.get()
, find the steps.
Step-1: We need to import
HttpClientModule
in our application module.
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientModule, ------ ], --------- }) export class AppModule { }
HttpClient
as given below.
constructor(private http: HttpClient) { }
get()
method.
return 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
to handle the HTTP response.
Observable: This is a RxJS API.
Observable
is a representation of any set of values over any amount of time. All Angular HttpClient
methods return Observable
response type. The Observable
provides pipe
method to execute RxJS operators such as map()
, catchError()
etc. The map()
applies a function to each value emitted by source Observable
and returns an instance of Observable
. The catchError()
is called when an error is occurred. The catchError()
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. The Promise
is a proxy for a value which is not known when the promise is created. The Promise
has methods such as then()
, catch()
etc. The HttpClient.get()
returns Observable
and to convert it into Promise
we need to call RxJS toPromise()
operator 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
.
HttpClient.get() with Observable
By defaultHttpClient.get()
returns Observable
of JSON response type.
getBooksWithObservable(): Observable<Book[]> { return this.http.get(this.url).pipe( map(this.extractData), catchError(this.handleErrorObservable) ) }
params
attribute as following.
getBooksWithObservable(category: string, writer: string): Observable<Book[]> { let httpParams = new HttpParams() .set('category', category) .set('writer', writer); return this.http.get(this.url, { params: httpParams }).pipe( map(this.extractData), catchError(this.handleErrorObservable) ) }
extractData()
method. The RxJS map()
is used to map response object into other object if needed.
private extractData(res: any) { let body = res; return body; }
catchError()
operator. Find our handleErrorObservable()
method.
private handleErrorObservable(error: any) { console.error(error.message || error); return throwError(error); }
throwError
is RxJS operator to throw error.
To display
Observable
in our HTML template we can go by two way.
1. Angular structural directive can directly use
Observable
with async
pipe. Find the code snippet of component.
this.observableBooks = this.bookService.getBooksWithObservable();
observableBooks
with ngFor
as following.
<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. Find the code snippet of component.
this.observableBooks = this.bookService.getBooksWithObservable(); this.observableBooks.subscribe( books => this.books = books, error => this.errorMessage = <any>error);
books
with ngFor
in HTML template as following.
<ul> <li *ngFor="let book of books" > Id: {{book.id}}, Name: {{book.name}} </li> </ul>
HttpClient.get() with Promise
Let us understand to usePromise
with HttpClient.get
.
getBooksWithPromise(): Promise<Book[]> { return this.http.get(this.url).toPromise() .then(this.extractData) .catch(this.handleErrorPromise); }
get()
method that returns Observable
. On this value we call RxJS toPromise()
operator that will convert it into Promise
. We can use then()
to change the response object. If there is any error, the catch()
method will execute. Find the handleErrorPromise()
method used in catch()
.
private handleErrorPromise (error: Response | any) { console.error(error.message || error); return Promise.reject(error.message || error); }
Promise
in 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 of component.
this.promiseBooks = this.bookService.getBooksWithPromise();
promiseBooks
in our HTML template using ngFor
with async
pipe as following.
<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 following.
this.promiseBooks = this.bookService.getBooksWithPromise(); this.promiseBooks.then( books => this.books = books, error => this.errorMessage = <any>error);
books
in HTML template using ngFor
as following.
<ul> <li *ngFor="let book of books" > Id: {{book.id}}, Name: {{book.name}} </li> </ul>
Complete Example
Find the complete example.book.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { map, catchError } from 'rxjs/operators'; import { Book } from './book'; @Injectable({ providedIn: 'root' }) export class BookService { url = "http://localhost:4200/assets/data/books.json"; constructor(private http: HttpClient) { } getBooksWithObservable(): Observable{ return this.http.get(this.url).pipe( map(this.extractData), catchError(this.handleErrorObservable) ) } getBooksWithPromise(): Promise { return this.http.get(this.url).toPromise() .then(this.extractData) .catch(this.handleErrorPromise); } private extractData(res: any) { let body = res; return body; } private handleErrorObservable(error: any) { console.error(error.message || error); return throwError(error); } private handleErrorPromise(error: Response | any) { console.error(error.message || error); return Promise.reject(error.message || error); } }
export interface Book { id: number; name: string; }
[ {"id": 1, "name": "Core Java"}, {"id": 2, "name": "Angular"}, {"id": 3, "name": "Hibernate"} ]
import { Component } 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 { observableBooks: Observable<Book[]>; books: Book[] = []; errorMessage = ''; constructor(private bookService: BookService) { this.observableBooks = this.bookService.getBooksWithObservable(); this.observableBooks.subscribe( books => this.books = books, error => this.errorMessage = 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 with "subscribe"</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'; import { BookService } from './book.service'; import { Book } from './book'; @Component({ selector: 'app-promise', templateUrl: './promise.component.html' }) export class PromiseComponent { promiseBooks: Promise<Book[]>; books: Book[] = []; errorMessage = ''; constructor(private bookService: BookService) { this.promiseBooks = this.bookService.getBooksWithPromise(); this.promiseBooks.then( books => this.books = books, error => this.errorMessage = 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 with "then"</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 { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { ObservableComponent } from './observable.component'; import { PromiseComponent } from './promise.component'; @NgModule({ imports: [ BrowserModule, HttpClientModule ], declarations: [ AppComponent, ObservableComponent, PromiseComponent ], providers: [ ], bootstrap: [ AppComponent ] }) export class AppModule { }
Run Application
To run the application, find the steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. 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
5. Access the URL http://localhost:4200
Find the print screen of the output.
