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

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

We'll learn to create and consume RESTful APIs in Angular 8 project. ... to Receive and Delete the Data in Angular 8 HttpClient Service; Update Data in Angular CRUD App ... Which stylesheet format would you like to use?

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

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

By Digamber Rawat Last updated on July 26, 2019

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

Table of Contents

  1. Getting Started
  2. Installation & Setup Angular 8 Project
  3. Set up Fake JSON Backend Server in Angular 8 App
  4. Import HttpClientModule in Angular 8
  5. Create Angular 8 Service to Consume RESTful APIs
  6. Make HTTP POST Request to Add the Data via HttpClient Service in Angular 8
  7. Make HTTP (GET & DELETE) Requests to Receive and Delete the Data in Angular 8 HttpClient Service
  8. Update Data in Angular CRUD App

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

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

&lt;/div&gt;

</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 =&gt; {return x.issue_name}).indexOf(data.issue_name);
   return this.bugService.DeleteBug(data.id).subscribe(res =&gt; {
    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">

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

&lt;/div&gt;

</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">

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

&lt;/div&gt;

</div>

Conclusion

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.

This post was originally published here

angular angular-js node-js api web-development

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

How to Implement Server Side Pagination with Angular 8 and Node.js

A simple example of how to implement server-side pagination in Angular 8 with a Node.js backend API.

Develop this one fundamental skill if you want to become a successful developer

Throughout my career, a multitude of people have asked me&nbsp;<em>what does it take to become a successful developer?</em>