Angular 14 HttpClient Service Example Tutorial

Angular HTTP Client example, In this guide, we will cover how to make HTTP Get, Post, Put, Update & Delete requests to communicate with the server to handle the data using angular http client API.

Moreover, you will learn to build a local server using the json-server package in an angular app.

The angular HTTP Client is a useful service to make HTTP requests, and it is available through HttpClientModule from the ‘@angular/common/http’ package.

The HTTP Client supports RxJs Observables. Every request made with HttpClient returns the observable response, which must be subscribed to get the answer or data. It relinquishes the pain of API testing, not just that it also handles the errors gracefully.

To take advantage of the Http client service, you have to inject the HttpClientModule inside the main app class module and even in the service or component from where you have to declare the CRUD operations.

Angular 14 HttpClient Service Example

Throughout this angular http service example, we would like to show you how to register http client service in the angular application, how to create service and build http service with CRUD methods.

On top of that, you will see angular httpclient post example, angular httpclient get example and angular httpclient get response headers example and that too from scratch.

  • Create an Angular App
  • Create Backend Server
  • Import HttpClientModule
  • Make Http POST, PUT, & DELETE Calls
  • Angular Http Headers
  • HttpClient Error Handling
  • Subscribe to HTTP Get
  • Receive the Http Response
  • Run Angular App

Create Angular App

Install Angular CLI on your machine:

npm install @angular/cli -g

Begin the first step with new angular app installation, skip this step if app already created:

ng new angular-demo-app

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Next, install Bootstrap UI pacakage:

npm i bootstrap

Open angular.json file, import the Bootstrap CSS:

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

Create JSON Backend Server

The json server library helps you set up a quick back-end for prototyping and mocking REST API.

Further, use the below command to install the json-server plugin:

npm install -g json-server

Next, construct a new backend directory in your project root, move inside the folder and create db.json file lastly put the below code within backend/database.json file:

{
    "users": [{
        "id": 1,
        "name": "Clifford Owens",
        "email": "clifford.owens@example.com",
        "phone": "(989)-433-3449"
    }, {
        "id": 2,
        "name": "Gabe Hamilton",
        "email": "gabe.hamilton@example.com",
        "phone": "(317)-303-3850"
    }, {
        "id": 3,
        "name": "Rene Sutton",
        "email": "rene.sutton@example.com",
        "phone": "(056)-128-7405"
    }, {
        "id": 4,
        "name": "Chester Caldwell",
        "email": "chester.caldwell@example.com",
        "phone": "(225)-256-0008"
    }]
}

Next, start the json server with the below command:

json-server --watch backend/database.json

You can check the resources or data of users located in backend/database.json file on the following URL:

http://localhost:3000/users

Import HttpClientModule in Angular

This step helps to ascertain how to import and register HttpClientModule in the src/app/app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Inject the dependency injector for HttpClient with supporting services for XSRF. Automatically imported by HttpClientModule.

Construct Angular Service with HttpClient

Further, execute the following command to generate a service file.

ng generate service crud

Open and update src/app/crud.service.ts file:

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

export class User {
  id: string;
  name: string;
  email: string;
  phone: number;
}

@Injectable({
  providedIn: 'root'
})

export class CrudService {

  endPoint = 'http://localhost:3000';

  constructor(private httpClient: HttpClient) { }

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

  getUsers(): Observable<User> {
    return this.httpClient.get<User>(this.endPoint + '/users')
    .pipe(
      retry(1),
      catchError(this.httpError)
    )
  }

  getUser(id): Observable<User> {
    return this.httpClient.get<User>(this.endPoint + '/users/' + id)
    .pipe(
      retry(1),
      catchError(this.httpError)
    )
  }  

  create(employee): Observable<User> {
    return this.httpClient.post<User>(this.endPoint + '/users', JSON.stringify(employee), this.httpHeader)
    .pipe(
      retry(1),
      catchError(this.httpError)
    )
  }  

  update(id, data): Observable<User> {
    return this.httpClient.put<User>(this.endPoint + '/users/' + id, JSON.stringify(data), this.httpHeader)
    .pipe(
      retry(1),
      catchError(this.httpError)
    )
  }

  delete(id){
    return this.httpClient.delete<User>(this.endPoint + '/users/' + id, this.httpHeader)
    .pipe(
      retry(1),
      catchError(this.httpError)
    )
  }

  httpError(error) {
    let msg = '';
    if(error.error instanceof ErrorEvent) {
      // client side error
      msg = error.error.message;
    } else {
      // server side error
      msg = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(msg);
    return throwError(msg);
  }

}

On top of the service file, import HttpClient and HttpHeaders modules from ‘@angular/common/http’.

HttpClient API is observable based, so to bind the create, read, update and delete HTTP requests with RxJS observable import Observable, throwError from rxjs module.

For managing error handling with Angular HttpClient, you need to import retry and catcherror operators from the rxjs/operators module.

Create a User model schema right after the imports.

Inject HttpClient inside the constructor with private value.

HTTP headers permit the client and the server to carry supplementary information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (:), then by its value. Whitespace before the value is disregarded.

Finally, we have created POST, PUT, and DELETE Request in Angular, respectively, with HttpClient.

The httpError method handles the errors in Angular when making Http requests using the HttpClient API.

Angular HTTP GET & Delete Example

The HTTP CRUD functions are created that we defined in the service file now. In this step, you will find out how to display user data by making HTTP Get request in angular.

Open and update following code in app.component.html file:

<table class="table table-bordered">
  <thead>
    <tr>
      <th scope="col">#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 user of Users">
      <td>{{user.id}}</td>
      <td>{{user.name}}</td>
      <td>{{user.email}}</td>
      <td>{{user.phone}}</td>
      <td>
        <span class="text-primary" (click)="remove(user.id)">Delete</span>
      </td>
    </tr>
  </tbody>
</table>

Open and update code in app.component.ts file:

import { Component, OnInit } from '@angular/core';
import { CrudService } from "./crud.service";

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

export class AppComponent implements OnInit {
  
  Users: any = [];

  constructor(public crudService: CrudService) { }

  ngOnInit() {
    this.fetchUsers()
  }  

  fetchUsers() {
    return this.crudService.getUsers().subscribe((data: {}) => {
      this.Users = data;
    })    
  }  

  remove(id) {
    this.crudService.delete(id).subscribe(res => {
      this.fetchUsers()
    })
  }

}

Run Angular App

Open the console, execute command to start the angular development server:

ng serve --open

Using the Bootstrap table component, we are displaying the data by fetching it from the server using an HTTP Get request; moreover, you can remove the user object using an HTTP Delete request.

Angular HttpClient Service Example

Conclusion

The Angular HttpClient API tutorial is over; in this tutorial, you learned how to make Http GET, POST, PUT & Update requests using angular Http client service.