Angular 8 HttpClient & Http Tutorial – Build, Consume RESTful API

By Digamber Rawat Last updated on

Angular 8 HttpClient Tutorial

Angular 8 HttpClient & Http tutorial is going to be discussed in this blog today. We’ll learn to create and consume RESTful APIs in Angular 8 project. To manage the data on the remote server, we make GET, POST, PUT and Delete using HttpClient API. We are required to import and setup HttpClient service in Angular 8 project to consume REST APIs.

To work with HttpClient service in Angular, you need to import the HttpClientModule in app.module.ts file. Then inject HttpClient service in constructor method after that you can hit the remote server via HTTP’s POST, GET, PUT and DELETE methods.

HttpClient in Angular 8

HttpClient API service is used to make communication between front-end web apps with backend services. This communication is done over HTTP protocol. Angular 8 HttpClient service makes the communication with remote server very easy. It needs to be imported via @angular/common/http package.

Benefits of HttpClient Service

  • Easy Testing
  • Typed Request & Response Objects
  • Request Interception
  • Response Interception
  • APIs Observable Support
  • Easy Error Handling

What Does Angular.io say About HttpClient?

“HttpClient is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).”

Angular 8 HttpClient Methods

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

#01 – Getting Started

Setup Node JS

In the first step, We’ll set up the development environment in our system for setting up an Angular 8 project from scratch.

Follow this tutorial to set up Node JS in your system: How To Install Node JS?

Node JS will allow us to install the required packages for this Angular 8 HttpClient tutorial.

In the next step, we’ll be installing Angular CLI with the help of Node Package Manager (NPM).

npm install @angular/cli -g

2. Installation & Setup Angular 8 Project

To create front-end of our demo app we need to install Angular 8 app. Run the below command in your terminal.

ng new angular8-httpclient-tutorial

# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? CSS

Once your project is downloaded, then get into the project folder.

cd angular8-httpclient-tutorial

We’ll also install Bootstrap 4 UI library in Angular 8 project using given below command.

npm install bootstrap

To use the Bootstrap 4 ui components go to angular.json file and replace the following code.

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

Create components in Angular 8 app to manage the data.

# ng g component components/add-issue
# ng g component components/edit-issue
# ng g component components/issue-list

Run the following command to start the app.

ng serve

#03 – Set up Fake JSON Backend Server in Angular 8 App

We are going to create a fake backend server using json-server NPM module in our Angular 8 app. This module will allow us to communicate with the server we can send and receive the data locally.

Run the below command to set fake json-server globally.

sudo npm install -g json-server

In the root folder of your Angular 8 project, create a folder by the name of backend and also create a file by the name of database.json. This file will have our fake JSON data.

mkdir backend && cd backend && touch database.json

In next step go to your database.json file and add some fake data.

{
  "bugtracking": [
    {
      "issue_name": "Table Improvement",
      "issue_message": "Issue tracking is awesome because of collaboration",
      "id": 1
    },
    {
      "issue_name": "Tooltip Issue",
      "issue_message": "Issue tracking is awesome because of collaboration",
      "id": 2
    }
  ]
}

Finally, we are done setting up a fake JSON server in our Angular 8 app, now run the command to start the fake JSON server.

json-server --watch backend/database.json

#  \{^_^}/ hi!

#  Loading backend/database.json
#  Done

#  Resources
#  http://localhost:3000/bugtracking

#  Home
#  http://localhost:3000

#  Type s + enter at any time to create a snapshot of the database
#  Watching...

If you are getting this response in your terminal that means you are ready to send and receive data using HttpClient service in Angular 8.

Check out the below urls

Resources: http://localhost:3000/bugtracking
Home: http://localhost:3000
Angular 8 Front-end: http://localhost:4200

4. Import HttpClientModule in Angular 8

This service configures the dependency injector for HttpClient with supporting services for XSRF.

To make the HTTP request to communicate with the server, we first import the HttpClientModule service in our Angular 8 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
   ]
})

#05 – Create Angular 8 Service to Consume RESTful APIs

In the next step, we are going to create Angular 8 service file, this file will allow us to consume RESTful API. We’ll import HttpClient, HttpHeaders services to make the HTTP request work. We’ll create CRUD operations and also write some error handling logic in it.

Angular 8 Service CRUD Tasks:

  • Create Bug
  • Show Bug List
  • Update Bug
  • Delete Bug

But before we create the service file we need to create an interface class in which we’ll define the data type of our bug tracking demo app.

Create Bug class to define data type:

mkdir shared && cd shared

Create a bug.ts file and paste the following code.

export class Bug {
   id: string;
   issue_name: string;
   issue_message: string;
}

Create BugService Class, run the below command:

ng g s shared/bug

Now, paste the below code in bug.service.ts file to create CRUD operation in our bug tracking app.

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

@Injectable({
  providedIn: 'root'
})

export class BugService {

  // Base url
  baseurl = 'http://localhost:3000';

  constructor(private http: HttpClient) { }

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

  // POST
  CreateBug(data): Observable<Bug> {
    return this.http.post<Bug>(this.baseurl + '/bugtracking/', JSON.stringify(data), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.errorHandl)
    )
  }  

  // GET
  GetIssue(id): Observable<Bug> {
    return this.http.get<Bug>(this.baseurl + '/bugtracking/' + id)
    .pipe(
      retry(1),
      catchError(this.errorHandl)
    )
  }

  // GET
  GetIssues(): Observable<Bug> {
    return this.http.get<Bug>(this.baseurl + '/bugtracking/')
    .pipe(
      retry(1),
      catchError(this.errorHandl)
    )
  }

  // PUT
  UpdateBug(id, data): Observable<Bug> {
    return this.http.put<Bug>(this.baseurl + '/bugtracking/' + id, JSON.stringify(data), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.errorHandl)
    )
  }

  // DELETE
  DeleteBug(id){
    return this.http.delete<Bug>(this.baseurl + '/bugtracking/' + id, this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.errorHandl)
    )
  }

  // Error handling
  errorHandl(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}`;
     }
     console.log(errorMessage);
     return throwError(errorMessage);
  }

}

Then go to app.module.ts file and import the Angular 8 service and inject into the providers array, like given below.

import { BugService } from 'shared/bug.service';

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [BugService],
  bootstrap: [...]
})

export class AppModule { }

#06 – Make HTTP POST Request to Add the Data via HttpClient Service in Angular 8

Let’s add the data in local server using HttpClient service in Angular 8. Go to components > add-issue.component.ts file and add the following code.

import { Component, OnInit, NgZone } from '@angular/core';
import { BugService } from '../../shared/bug.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

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

export class AddIssueComponent implements OnInit {
  issueForm: FormGroup;
  IssueArr: any = [];

  ngOnInit() {
    this.addIssue()
  }

  constructor(
    public fb: FormBuilder,
    private ngZone: NgZone,
    private router: Router,
    public bugService: BugService
  ){ }

  addIssue() {
    this.issueForm = this.fb.group({
      issue_name: [''],
      issue_message: ['']
    })
  }

  submitForm() {
    this.bugService.CreateBug(this.issueForm.value).subscribe(res => {
      console.log('Issue added!')
      this.ngZone.run(() => this.router.navigateByUrl('/issues-list'))
    });
  }

}

Go to components > add-issue.component.html file and add the following code.

<div class="container wrapper wrapper2">
    <div class="row">

        <!-- Form -->
        <div class="col-md-12">
            <h3>Add Issue</h3>
            <form [formGroup]="issueForm" (ngSubmit)="submitForm()" novalidate>
                <div class="form-group">
                    <label>Issue</label>
                    <input type="text" formControlName="issue_name" class="form-control" maxlength="20">
                </div>
                <div class="form-group">
                    <label>Issue Details</label>
                    <textarea class="form-control" formControlName="issue_message" rows="3" maxlength="50"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>

    </div>
</div>

Now, we can easily create an issue and save it to the local server using HttpClient and HttpHeaders Angular 8 services.

#07 – Make HTTP (GET & DELETE) Requests to Receive and Delete the Data in Angular 8 HttpClient Service

In this part of the tutorial, we are going to learn how to receive and delete the data via HttpClient API in an Angular CRUD app. We’ll use the Bootstrap 4 table to show the data on the frontend.

Go to components > issue-list.component.ts file and paste the following code.

import { Component, OnInit } from '@angular/core';
import { BugService } from '../../shared/bug.service';

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

  IssuesList: any = [];


  ngOnInit() {
    this.loadEmployees();
  }

  constructor(
    public bugService: BugService
  ){ }

   // Issues list
   loadEmployees() {
    return this.bugService.GetIssues().subscribe((data: {}) => {
      this.IssuesList = data;
    })
  }

    // Delete issue
    deleteIusse(data){
      var index = index = this.IssuesList.map(x => {return x.issue_name}).indexOf(data.issue_name);
       return this.bugService.DeleteBug(data.id).subscribe(res => {
        this.IssuesList.splice(index, 1)
         console.log('Issue deleted!')
       })
    }

}

Go to components > issue-list.component.html file and paste the following code.

<div class="container wrapper">
    <div class="row">

        <!-- Issue table -->
        <div class="col-md-12">
            <div class="inner">
                <h3>My Issues</h3>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Issue Name</th>
                            <th scope="col">Issue Details</th>
                            <th scope="col">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let issues of IssuesList">
                            <th scope="row">{{issues.id}}</th>
                            <td>{{issues.issue_name}}</td>
                            <td>{{issues.issue_message}}</td>
                            <td>
                                <button type="button" class="btn btn-success btn-sm move-right" [routerLink]="['/edit-issue/', issues.id]">Edit</button>
                                <button type="button" class="btn btn-danger btn-sm" (click)="deleteIusse(issues)">Remove</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

#08 – Update Data in Angular CRUD App

In this final part of this tutorial, we are going to learn how to make PUT Request via HttpClient Angular 8 service to update the data on the server.

Head over to the components > edit-issue.component.ts file and paste the following code.

import { Component, OnInit, NgZone } from '@angular/core';
import { BugService } from '../../shared/bug.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';

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

export class EditIssueComponent implements OnInit {
  IssuesList: any = [];
  updateIssueForm: FormGroup;
  
  ngOnInit() {
    this.updateForm()
  }

  constructor(
    private actRoute: ActivatedRoute,    
    public bugService: BugService,
    public fb: FormBuilder,
    private ngZone: NgZone,
    private router: Router
  ) { 
    var id = this.actRoute.snapshot.paramMap.get('id');
    this.bugService.GetIssue(id).subscribe((data) => {
      this.updateIssueForm = this.fb.group({
        issue_name: [data.issue_name],
        issue_message: [data.issue_message]
      })
    })
  }

  updateForm(){
    this.updateIssueForm = this.fb.group({
      issue_name: [''],
      issue_message: ['']
    })    
  }

  submitForm(){ 
    var id = this.actRoute.snapshot.paramMap.get('id');
    this.bugService.UpdateBug(id, this.updateIssueForm.value).subscribe(res => {
      this.ngZone.run(() => this.router.navigateByUrl('/issues-list'))
    })
  }

}

Head over to the components > edit-issue.component.html file and paste the following code.

<div class="container wrapper wrapper2">
    <div class="row">

        <!-- Form -->
        <div class="col-md-12">
            <h3>Add Issue</h3>
            <form [formGroup]="updateIssueForm" (ngSubmit)="submitForm()" novalidate>
                <div class="form-group">
                    <label>Issue</label>
                    <input type="text" formControlName="issue_name" class="form-control" maxlength="20">
                </div>
                <div class="form-group">
                    <label>Issue Details</label>
                    <textarea class="form-control" formControlName="issue_message" rows="3" maxlength="50"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Update</button>
            </form>
        </div>

    </div>
</div>

Finally, we’ve completed the Angular 8 HttpClient & Http Tutorial. In this tutorial, we’ve learned how to make HTTP POST, GET, DELETE & PUT request to manage the data on the server along with some basic error handling. If you like this tutorial please share it with others. You can found GitHub repo here.

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.

Hire Me