Angular 16 HttpClient & Http Services Example Tutorial

Last Updated on by in Angular Tutorial
In Angular, HttpClient is an API that allows to perform HTTP requests. HTTP requests are made to create communication between the client and server. The HttpClient service is available as an injectable class and comes with various methods (GET, POST, PUT, UPDATE, DELETE, etc.) to send HTTP requests in Angular.In this tutorial, we will walk you through how to send HTTP requests in an Angular application using the HttpClient and HttpClientModule services. To understand how to make HTTP requests in Angular, we will create a basic employee management system using the Angular framework.

Furthermore, we will cover the following topics, considering the HttpClient API:

  • How to make an HTTP GET request in Angular
  • How to send an HTTP POST request in Angular
  • How to send an HTTP PUT request to update data on a server in Angular
  • How to make an HTTP DELETE request in Angular to delete data or resources on a server

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

Angular 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?
Choose SCSS 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

Remove Angular TypeScript Errors

To get rid from the errors:

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set following properties to false in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
},
  "angularCompilerOptions": {
    "strictTemplates": false
  }

I’ll be using Bootstrap 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.scss"
          ]

Now, we have to generate the following components.

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

Configure JSON Server in Angular

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 install -g json-server

Then, create a file at the root of your angular project, make sure to name the file 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 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 { EmployeeListComponent } from './employee-list/employee-list.component';
const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'create-employee' },
  { path: 'create-employee', component: EmployeeCreateComponent },
  { path: 'employees-list', component: EmployeeListComponent },
  { path: 'employee-edit/:id', component: EmployeeEditComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Enable the routes within view, add the following code in app.component.html file.

<router-outlet></router-outlet>

Make sure to import the import AppRoutingModule from ‘./app-routing.module’ in app.module.ts file.;

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.

Besides, here is the complete app.module.ts file, which contains routing, forms, app components and http modules.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { EmployeeCreateComponent } from './employee-create/employee-create.component';
import { EmployeeEditComponent } from './employee-edit/employee-edit.component';
import { EmployeeListComponent } from './employee-list/employee-list.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent,
    EmployeeCreateComponent,
    EmployeeEditComponent,
    EmployeeListComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Create Angular Service

In order to create consume RESTful API using Angular 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 i 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: any): 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: any): 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: any, employee: any): 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: any) {
    return this.http
      .delete<Employee>(this.apiURL + '/employees/' + id, this.httpOptions)
      .pipe(retry(1), catchError(this.handleError));
  }
  // Error handling
  handleError(error: any) {
    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(() => {
      return errorMessage;
    });
  }
}

Create Data using Angular HTTP POST Request

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

<div class="container custom-container mb-5">
    <div class="col-md-12">
      <h3 class="mb-3 text-center">Create Employee</h3>
  
      <div class="mb-3 ">
        <input type="text" [(ngModel)]="employeeDetails.name" class="form-control" placeholder="Name">
      </div>
  
      <div class="mb-3 ">
        <input type="text" [(ngModel)]="employeeDetails.email" class="form-control" placeholder="Email">
      </div>
  
      <div class="mb-3 ">
        <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(employeeDetails)">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.scss'],
})
export class EmployeeCreateComponent implements OnInit {
  @Input() employeeDetails = { name: '', email: '', phone: 0 };
  constructor(public restApi: RestApiService, public router: Router) {}
  ngOnInit() {}
  addEmployee(dataEmployee: any) {
    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.

Add code in employee-list.component.html file.

<div class="container custom-container-2 mt-5">
  <!-- 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 btn btn-sm btn-outline-primary me-2"
                routerLink="/employee-edit/{{ employee.id }}"
                >Edit</span
              >
              <span
                class="delete edit btn btn-sm btn-outline-danger"
                (click)="deleteEmployee(employee.id)"
                >Delete</span
              >
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

Add code in employee-list.component.ts file.

import { Component, OnInit } from '@angular/core';
import { RestApiService } from '../shared/rest-api.service';
@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.scss'],
})
export class EmployeeListComponent 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: any) {
    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="mb-3">
      <input
        type="text"
        [(ngModel)]="employeeData.name"
        class="form-control"
        placeholder="Name"
      />
    </div>
    <div class="mb-3">
      <input
        type="text"
        [(ngModel)]="employeeData.email"
        class="form-control"
        placeholder="Email"
      />
    </div>
    <div class="mb-3">
      <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.scss']
})
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

Today, we have learned how to create and consume RESTful API in Angular using HttpClient service. HttpClient offers powerful mechanism and turns out be a useful method or API service in Angular. It enables client to communicate with the remote server. In this post, we taught you to make HTTP request in Angular HttpClient features.

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

Here are complete list of Angular HttpClient methods:

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

Download the full code of this tutorial from GitHub.

Reference: https://angular.io/api/common/http/HttpClient

Reference: https://www.npmjs.com/package/json-server

❤️ Checkout Popular CSS Collection

Digamber - Author positronX.io

Digamber, the founder of PositronX, is a certified web developer with over 10 years of experience. He possesses a curiosity for learning new things and enjoys playing cricket on his days off.