Learn to use angular HttpClient
service to fetch data from online REST APIs and return it as Observable
object/array. Upon any data event, the subscribers of observable
will react.
Table of Contents HTTPClient Setup Create service which return Observable Create observer which subscribe to Observable View HTML Template Demo
HTTPClient Setup
To use HTTPClient
service, you need to do two steps:
-
Import HttpClientModule in root module
Import
HttpClientModule
module from@angular/common/http
package and add it’s entry inimports
attribute of@NgModule
.import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
-
Inject HttpClient in service constructor
Now inject actual
HttpClient
service in your service code as start using it.import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class EmployeeService { constructor(private http: HttpClient) { } }
Create service which return Observable
We will consume the REST API created with REST mock server. Let’s edit the code of employee service class and return Observable
from it.
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Employee } from '../model/employee'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class EmployeeService { constructor(private http: HttpClient) { } public getEmployees(): Observable<Employee[]> { const url = 'http://localhost:3000/employees'; return this.http.get<Employee[]>(url); } }
Above code, hits the REST API "/employees"
and fetch employee
array. It then return the employee array as observable collection. Any method can subscribe to it to listen data events on this array.
FYI, Employee
is model class to store data.
export class Employee { public id: number; public name: string; public status: string; constructor(id:number, name:string, status:string) { this.id = id; this.name = name; this.status = status; } }
Create observer which subscribe to Observable
We will create subscriber in component file. It will read the data from observable array and assign to model attribute. Model attribute can be used to map data from UI.
import { Component } from '@angular/core'; import { EmployeeService } from './service/employee.service'; import { Employee } from './model/employee'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; employees = new Array<Employee>(); constructor( empService:EmployeeService ) { empService.getEmployees().subscribe(response => { this.employees = response.map(item => { return new Employee( item.id, item.name, item.status ); }); }); } }
View HTML Template
Time to update view HTML which will render employee array
data as soon as it’s available.
<h1> Angular HTTP Service Example </h1> <table border="1" style="width: 33%"> <tr> <th>Id</th> <th>Name</th> <th>Status</th> </tr> <tr *ngFor="let emp of employees"> <td>{{ emp.id }}</td> <td>{{ emp.name }}</td> <td>{{ emp.status }}</td> </tr> </table>
Demo
To test the above written code, you will to start mock REST server as well as angular application.
- Start Mock server with this command.
$ json-server --watch 'E:\ngexamples\db.json'
- Start angular application with command.
$ ng serve
Check the application in browser.

Drop me your comments in sourcecode.
Happy Learning !!