Angular 14 Consume REST API with HttpClient Tutorial

Last updated on: by Digamber
Angular HttpClient tutorial; In Angular, we use HttpClient API to handle the HTTP requests. In this tutorial, you will learn how to trigger HTTP requests in Angular using the HttpClient API.

HTTP protocol gives ample freedom to communicate with a server; almost every web application needs to develop consensus to manage the data on the remote server.

We will learn to create and consume RESTful APIs in Angular application. 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 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

HttpClient API service is used to make communication between front-end web apps with backend services. This communication is done over HTTP protocol.

Angular 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 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 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 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 Project

To create front-end of our demo app we need to install Angular app.

Run the below command in your terminal.

ng new angular-httpclient-demo
# ? 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 angular-httpclient-demo

In order to remove strict type warnings or errors make sure to set “strict”: false and "strictTemplates": false under compilerOptions and angularCompilerOptions properties in tsconfig.json file.

We’ll also install Bootstrap 4 UI library in Angular 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 app to manage the data.

ng g c components/add-issue
ng g c components/edit-issue
ng g c components/issue-list

You have to add the given code into the app.component.html file.

<router-outlet></router-outlet>

Now, you need to go to app-routing.module.ts file and define the routes.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AddIssueComponent } from './components/add-issue/add-issue.component';
import { EditIssueComponent } from './components/edit-issue/edit-issue.component';
import { IssueListComponent } from './components/issue-list/issue-list.component';
const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'add-issue' },
  { path: 'add-issue', component: AddIssueComponent },
  { path: 'edit-issue/:id', component: EditIssueComponent },
  { path: 'issues-list', component: IssueListComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

#03 – Set up Fake JSON Backend Server

We are going to create a fake backend server using json-server NPM module in our Angular 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.

 npm install -g json-server

In the root folder of your Angular 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 angular app, now run the command to start the fake JSON server.

json-server --watch 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.

Check out the below urls

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

4. Import HttpClientModule

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 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 Service to Consume RESTful APIs

In the next step, we are going to create Angular 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 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 app/shared and create Bug class and add data type in shared/bug.ts file:

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 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(() => {
      return errorMessage;
    });
  }
}

Then go to app.module.ts file and import the Angular 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

Let’s add the data in local server using HttpClient service in Angular. 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.

#07 – Make HTTP (GET & DELETE) Requests

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 also 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>

Run the following command to start the app.

ng serve --open

Angular 13 Consume REST API with HttpClient Tutorial

Conclusion

Finally, we’ve completed the Angular 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

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.