Angular 7 HttpClient & Http Services to Consume RESTful API

By Digamber Rawat Last updated on

Hello folks, today I am going to show you how you can consume RESTful API in Angular 7 using HttpClient service. HttpClient service is a very useful API in Angular 6 & 7 to communicate with the remote server.

HttpClient API 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.

HttpClient service methods in Angular 7

  • 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 6 | 7 app?
  • How to make a request using a local server with JSON server NPM package.
  • How to make GET, POST, PUT & DELETE request with Angular 6 | 7 using HttpClient API

1. Prerequisite

– Setup Node JS development environment

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?

2. Install Angular CLI

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

3. How to set up Angular 7 Project using Angular CLI from scratch?

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

It’s time to setup Angular 7 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 7 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"
          ]

Start your project using given below command.

ng serve --open

Generate components for Angualr 7 Demo App

ng g c employee-create
ng g c employee-details
ng g c employee-update
ng g c employees-list

4. Set up Routing Service in Angular 7 Project

For navigating between components in Angular 7 we need to activate routing service in our applicaiton, to do that visit app-routing.module.ts file and include the given below code.

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

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

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

export class AppRoutingModule { }

5. How to Set up a JSON Server in Angular 7 project using NPM package?

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

Let’s, set up a JSON server globally in our project, run the following command in Angular CLI.

sudo npm install -g json-server

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

mkdir 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.

6. How to Set up HttpClient API in Angular 7 App for Consuming RESTful 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 6 | 7 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 your Angular 7 application.

7. How to Create Angular Service for consuming RESTful API using Angular 7 HttpClient Service?

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

Functionalites to be covered:

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

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

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;
}

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);
  }

}

8. Access HttpClient API from Angular 7 Component

We’ve successfully created RESTful services using Angualr 7 HttpClient API, its time to access rest-api.service.ts via Angular 7 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 an Employee by Making an HTTP POST Request in Angular 7

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 7 component.

9. Send HTTP GET and DELETE Requests in Angular 7 to Manage Employees List

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()
      })
    }
  }  

}

10. Make HTTP PUT Request in Angular 7 to Update Data

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

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 7 HttpClient application in the browser, just type ng serve in the terminal.

11. GitHub Project Files

GitHub Resources

That’s it for now…If this tutorial has been helpful to you then must share it with others. If you have any suggestion or wanna request a tutorial then drop me a mail..

If you find any issue related to this tutorial then report it here, your little effort will help me to make this tutorial better for our community.

Have a good day, Keep learning

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.