Angular 12 HttpClient & Http Services Example Tutorial

Last updated on: by Editorial Team
Hello folks, today I am going to show you how you can consume RESTful API in Angular 12 using HttpClient service. HttpClient service is a very useful API in Angular to communicate with the remote server.

Angular 12 HttpClient Features

  • Observable Support
  • Hassle Free API Testing
  • Smooth Requests & Response Mechanism
  • Better Error Handling

HttpClient is an injectable service, it comes with the various powerful methods to communicate with the remote server. HttpClient API can send Http POST, GET, PUT and DELETE requests easily.

Angular 12 HttpClient Methods

  • request()
  • delete()
  • get()
  • head()
  • jsonp()
  • options()
  • patch()
  • post()
  • put()

I’ll be showing you the practical examples of standard HTTP methods like GET, PUT, POST and DELETE, these methods allow you to communicate with a REST API server.

By the end of this tutorial, you’ll be able to understand. How to set up the HttpClientModule in Angular app? make a request using a local server with JSON server NPM package, and how to make GET, POST, PUT & DELETE request with Angular using HttpClient API.

Angular 12 HttpClient Services Example

  • Install Angular CLI
  • Configure Fake JSON Server in Angular
  • Enable Routing Service in Angular
  • Configure Angular HttpClient
  • Create Angular Service for Consuming RESTful API using Angular HttpClient API
  • Access HttpClient API from Angular Component
  • Send HTTP GET and DELETE Requests in Angular to Manage Data
  • Make HTTP PUT Request in Angular to Update Data

Create Angular Project

In order to create this demo app you must have Node JS development environment set up in your machine.

Please follow this link How to Set up Node JS Development Environment?

Angular projects are developed using Angular CLI, it’s an official tool. Hit the given below command to install the Angular CLI, ignore if Angular CLI is already installed.

npm install @angular/cli -g

I will be creating an employee record management system with Angular, in this demo app i will consume RESTful API via HttpClient service.

It’s time to setup Angular project, run the following command in Angular CLI.

ng new angular-httpclient-app

It will ask you the following questions…

Would you like to add Angular routing?
Select y and Hit Enter.

Which stylesheet format would you like to use? (Use arrow keys)
Choose CSS and hit Enter

After that your project will start creating, Once the project is created then don’t forget to get into the project’s folder.

cd angular-httpclient-app

I’ll be using Bootstrap 4 CSS framework with Angular for consuming RESTful API with HttpClient service. Hit the following command to get the Bootstrap in your Angular app.

npm install bootstrap

After that, Go to angular.json file and replace the given below code with “styles”: [ ] array.

"styles": [
            "node_modules/bootstrap/dist/css/bootstrap.min.css",
            "src/styles.css"
          ]

Generate components for Angualr 7 Demo App

ng g c employee-create
ng g c employee-edit
ng g c employee-list

Configure JSON Server in Angular 12

We are going to create a fake server for testing our Angular app, so we will be taking help of json-server NPM package to sort out our problem.

Install JSON server in our project, run the following command in Angular CLI.

npm i json-server --save

Then, create a folder by the name of server and keep your database file in it to manage the APIs locally.

mkdir server && cd server
touch server/db.json

Once the db.json file is created then add some data in it.

{
  "employees": [{
    "id": 1,
    "name": "Tony Stark",
    "email": "tony@mcu.com",
    "phone": "001-123-4567"
  }, {
    "id": 2,
    "name": "Black Widow",
    "email": "black-widow@mcu.com",
    "phone": "001-123-4568"
  }]
}

After that run the following command to run the JSON server.

json-server --watch server/db.json

Now if you make any request with Angualr 7 Http post, put, get or delete your db.json file will get updated locally.

You can check your local db.json file on this URL http://localhost:3000/employees.

Enable Routing Service in Angula

For navigating between components in Angular we need to activate routing service in our application, to enable routes go to app-routing.module.ts file and add the following code.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeCreateComponent } from './employee-create/employee-create.component';
import { EmployeeEditComponent } from './employee-edit/employee-edit.component';
import { EmployeesListComponent } from './employees-list/employees-list.component';

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'create-employee' },
  { path: 'create-employee', component: EmployeeCreateComponent },
  { path: 'employees-list', component: EmployeesListComponent },
  { path: 'employee-edit/:id', component: EmployeeEditComponent }  
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Import HttpClient API

In this tutorial, I will give you the demo to access the external server to fetch the data using the RESTful API in Angular with HttpClient service. In order to use HttpClient API to make the communication with Http remote server, you must set up this service in your Angular app.

Go to app.module.ts and paste the following code.

import { HttpClientModule } from '@angular/common/http';

Include the HttpClientModule in @NgModule's imports array.

@NgModule({
  imports: [
    HttpClientModule
   ]
})

You’ve injected the HttpClientModule in your application, now you can use it easily in Angular app.

Create Angular Service

In order to create consume RESTful API using Angular 12 HttpClient service we need to create a service file in our app. This file will hold the core logic of our demo application.

Functionalities to be covered:

  • Create Employee
  • Delete Employee
  • Update Employee
  • Manage Employee List

In order to create CRUD operations using RESTful API in Angular, we need to generate employee.ts class and rest-api.service.ts files.

Next, generate employee interface class:

ng g cl shared/Employee

Go to shared/employee.ts and define data types within the Employee class.

export class Employee {
   id: string;
   name: string;
   email: string;
   phone: number;
}

Next, generate RestApiService class:

ng g s shared/rest-api

I will be writing down core logic in this file for consuming RESTful API using HttpClient API. We will also use RxJS to handle asynchronous operations and errors in this demo app.

Let’s go to shared/rest-api.service.ts file and add the following code.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from '../shared/employee';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class RestApiService {
  
  // Define API
  apiURL = 'http://localhost:3000';

  constructor(private http: HttpClient) { }

  /*========================================
    CRUD Methods for consuming RESTful API
  =========================================*/

  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }  

  // HttpClient API get() method => Fetch employees list
  getEmployees(): Observable<Employee> {
    return this.http.get<Employee>(this.apiURL + '/employees')
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // HttpClient API get() method => Fetch employee
  getEmployee(id): Observable<Employee> {
    return this.http.get<Employee>(this.apiURL + '/employees/' + id)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

  // HttpClient API post() method => Create employee
  createEmployee(employee): Observable<Employee> {
    return this.http.post<Employee>(this.apiURL + '/employees', JSON.stringify(employee), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

  // HttpClient API put() method => Update employee
  updateEmployee(id, employee): Observable<Employee> {
    return this.http.put<Employee>(this.apiURL + '/employees/' + id, JSON.stringify(employee), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // HttpClient API delete() method => Delete employee
  deleteEmployee(id){
    return this.http.delete<Employee>(this.apiURL + '/employees/' + id, this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

  // Error handling 
  handleError(error) {
     let errorMessage = '';
     if(error.error instanceof ErrorEvent) {
       // Get client-side error
       errorMessage = error.error.message;
     } else {
       // Get server-side error
       errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
     }
     window.alert(errorMessage);
     return throwError(errorMessage);
  }

}

Access HttpClient from Angular Component

We’ve successfully created RESTful services using Angular 8/9/10 HttpClient API, its time to access rest-api.service.ts via Angular components.

Go to your app.module.ts file and add the following code, this file holds the core services to run our demo app.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

// HttpClient module for RESTful API
import { HttpClientModule } from '@angular/common/http';

// Routing module for router service
import { AppRoutingModule } from './app-routing.module';

// Forms module
import { FormsModule } from '@angular/forms';

// Components
import { EmployeeCreateComponent } from './employee-create/employee-create.component';
import { EmployeeEditComponent } from './employee-edit/employee-edit.component';
import { EmployeesListComponent } from './employees-list/employees-list.component';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeCreateComponent,
    EmployeeEditComponent,
    EmployeesListComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Create Data using Angular 12 HTTP POST Request

Go to employee-create.component.html add the following code.

<div class="container custom-container">
  <div class="col-md-12">
    <h3 class="mb-3 text-center">Create Employee</h3>

    <div class="form-group">
      <input type="text" [(ngModel)]="employeeDetails.name" class="form-control" placeholder="Name">
    </div>

    <div class="form-group">
      <input type="text" [(ngModel)]="employeeDetails.email" class="form-control" placeholder="Email">
    </div>

    <div class="form-group">
      <input type="text" [(ngModel)]="employeeDetails.phone" class="form-control" placeholder="Phone">
    </div>

    <div class="form-group">
      <button class="btn btn-success btn-lg btn-block" (click)="addEmployee()">Create Employee</button>
    </div>

  </div>
</div>

Go to employee-create.component.ts file and add the following code.

import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { RestApiService } from "../shared/rest-api.service";

@Component({
  selector: 'app-employee-create',
  templateUrl: './employee-create.component.html',
  styleUrls: ['./employee-create.component.css']
})
export class EmployeeCreateComponent implements OnInit {

  @Input() employeeDetails = { name: '', email: '', phone: 0 }

  constructor(
    public restApi: RestApiService, 
    public router: Router
  ) { }

  ngOnInit() { }

  addEmployee(dataEmployee) {
    this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
      this.router.navigate(['/employees-list'])
    })
  }

}

By adding given above code in employee create component, we can easily create an employee by making an HTTP POST request via Angular component.

Send HTTP GET and DELETE Requests

In this section i am going to manage employees list which we have created above. I will be using our RESTful API service by sending get() and delete() request via our custom apis.

employees-list.component.html

<div class="container custom-container-2">

  <!-- Show it when there is no employee -->
  <div class="no-data text-center" *ngIf="Employee.length == 0">
    <p>There is no employee added yet!</p>
    <button class="btn btn-outline-primary" routerLink="/create-employee">Add Empoyee</button>
  </div>

  <!-- Employees list table, it hides when there is no employee -->
  <div *ngIf="Employee.length !== 0">
    <h3 class="mb-3 text-center">Employees List</h3>

    <div class="col-md-12">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">User Id</th>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">Phone</th>
            <th scope="col">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let employee of Employee">
            <td>{{employee.id}}</td>
            <td>{{employee.name}}</td>
            <td>{{employee.email}}</td>
            <td>{{employee.phone}}</td>
            <td>
              <span class="edit" routerLink="/employee-edit/{{employee.id}}">Edit</span>
              <span class="delete" (click)="deleteEmployee(employee.id)">Delete</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

  </div>

</div>

employees-list.component.ts

import { Component, OnInit } from '@angular/core';
import { RestApiService } from "../shared/rest-api.service";

@Component({
  selector: 'app-employees-list',
  templateUrl: './employees-list.component.html',
  styleUrls: ['./employees-list.component.css']
})
export class EmployeesListComponent implements OnInit {

  Employee: any = [];

  constructor(
    public restApi: RestApiService
  ) { }

  ngOnInit() {
    this.loadEmployees()
  }

  // Get employees list
  loadEmployees() {
    return this.restApi.getEmployees().subscribe((data: {}) => {
      this.Employee = data;
    })
  }

  // Delete employee
  deleteEmployee(id) {
    if (window.confirm('Are you sure, you want to delete?')){
      this.restApi.deleteEmployee(id).subscribe(data => {
        this.loadEmployees()
      })
    }
  }  

}

Update Data

I am going to send HTTP PUT Request in Angular to update current employee data in our little demo app, It’s pretty simple just follow the following steps.

Update code in employee-edit.component.html:

<div class="container custom-container">
  <div class="col-md-12">
    
    <h3 class="mb-3 text-center">Update Employee</h3>

    <div class="form-group">
      <input type="text" [(ngModel)]="employeeData.name" class="form-control" placeholder="Name">
    </div>

    <div class="form-group">
      <input type="text" [(ngModel)]="employeeData.email" class="form-control" placeholder="Email">
    </div>

    <div class="form-group">
      <input type="text" [(ngModel)]="employeeData.phone" class="form-control" placeholder="Phone">
    </div>

    <div class="form-group">
      <button class="btn btn-success btn-lg btn-block" (click)="updateEmployee()">Update Employee</button>
    </div>
    
  </div>
</div>

employee-edit.component.ts

import { Component, OnInit } from '@angular/core';
import { RestApiService } from "../shared/rest-api.service";
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-employee-details',
  templateUrl: './employee-edit.component.html',
  styleUrls: ['./employee-edit.component.css']
})

export class EmployeeEditComponent implements OnInit {
  id = this.actRoute.snapshot.params['id'];
  employeeData: any = {};

  constructor(
    public restApi: RestApiService,
    public actRoute: ActivatedRoute,
    public router: Router
  ) { 
  }

  ngOnInit() { 
    this.restApi.getEmployee(this.id).subscribe((data: {}) => {
      this.employeeData = data;
    })
  }

  // Update employee data
  updateEmployee() {
    if(window.confirm('Are you sure, you want to update?')){
      this.restApi.updateEmployee(this.id, this.employeeData).subscribe(data => {
        this.router.navigate(['/employees-list'])
      })
    }
  }

}

Now you can test your Angular HttpClient application in the browser, just type ng serve in the terminal.

Run Angular Application

Start your project using given below command.

ng serve --open

Conclusion

That’s it for now…If this tutorial has been helpful to you then must share it with others.

Download the full code of this tutorial from GitHub.

Have a good day, Keep learning.