• Angular
  • React
  • NextJs
  • Sass

Angular HttpClient get Example

By Webrecto, September 17, 2023

In this article, we will learn about the Angular httpClient class and his .get() method to perform requests and responses. We know that most of the front-end applications communicate with back-end services over the HTTP protocol.

Angular HttpClient get Example

Features of HttpClient

  • 1: The httpClient is a built-in service class, It is part of @angular/common/http package.
  • 2: The httpClient performs HTTP requests and responses in the Angular application.
  • 3: The HttpClient is an improved replacement for HTTP and it was introduced in the Angular 4.3.0 version.
  • 4: In the Angular application for using httpClient, we need to import HttpClientModule in the main application app module from the @angular/common/http package.
  • 5: We inject HttpClientModule inside the import array after BrowserModule in the app module. We can not add in import arry before BrowserModule.
  • 6:The HttpClient service class is included in the HttpClientModule that is used to initiate HTTP requests and responses in Angular applications.
  • 7: To use HttpClient in the application, we need to import httpClient in the component or services file from the angular package. After that, we inject the httpClient class in the constructor for using the inbuilt httpClient method.
  • 8: In angular, the HttpClient class has several built-in methods to communicate with the back-end server via HTTP protocol. like get(), post(), put(), and delete(). All methods are performed in the application for data send, get, update, and delete.

Here in this article, I will provide the use of the HttpClient.get() method in detail. I will use Angular In-Memory Web API for the web service test URL.

Use the HttpClient.get() method

The httpClient is an injectable class that performs HTTP GET requests, It uses the HttpClient.get() method. In the Angular application, the HttpClient.get() method sends an HTTP request to the server to fetch data through API.
After the request is successful, The server returns an observable type response. The Observable is lazy in nature, without subscribing to the observable, the service will not call. When we subscribe to this observable object, an HTTP GET request is executed on the server.

Syntax of HttpClient GET method

get(url: string, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: HttpObserve;
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
    withCredentials?: boolean;
} = {}): Observable 

In the above syntax, according to Angular doc, we pass two arguments in the get() method, one is the endpoint URL and the other is the option object. Here we will describe all about the parameter.

url: We set API endpoint URL.

options: The second parameter is object type. The HTTP options to send with the request.

headers: The header is of HttpHeaders types. It sets header information for the http GET request.

observe: It defines whether we want a complete response or body only or events only.

params: It is of HttpParams type. It sets parameters in the URL for HTTP GET requests.

Set dependency for HttpClient GET method

Here we will set all necessary dependencies for call HttpClient.get() method.

Step 1: Import HttpClientModule

We import HttpClientModule from @angular/common/http library in the app.module.ts file. Next, We declare HttpClientModule in the imports array.

app.module.ts

import { NgModule } from  '@angular/core';
import { BrowserModule } from  '@angular/platform-browser';
import { AppComponent } from  './app.component';
import { HttpClientModule } from  '@angular/common/http';

@NgModule({
imports: [
 BrowserModule,
 HttpClientModule  //imported the module
],
providers: [],
 bootstrap: [AppComponent]
})
export  class  AppModule { }

Step 2: Injecting HttpClient in Component or Service

We can directly inject HttpClient in component or service files for the use of httpClient methods. We inject HttpClient into the constructor to create an object to the httpClient class. The HttpClient is imported from @angular/common/http library.

service.ts

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

@Injectable({
 providedIn:  'root'
})

export class HttpService {

private url = ''; // here we can set API url

constructor(private http: HttpClient) { }

getEmployeeDetails(): Observable {
    return this.http.get(); // it will return observable type data
 } 
}

We have two types of data for requesting by the get method. One is JSON type data and the other is text type data.

By HttpClient.get() requesting JSON type data

I have created a sample type of JSON data for company details.

 //JSON data
    {
      companyId: 11, companyName: 'WebRecto',
      enployee: [
        { id: '2236', name: 'Ashutosh', department: 'Java Team', profile: 'Module Lead' },
        { id: '2237', name: 'Shobhit', department: 'UI Team', profile: 'Team Lead' },
      ]
    };

I created one API URL to access JSON data from the server, the API URL communicates with the server to fetch data.

companydetails = "/api/companyDetails"; // API url for fetch data

In the service file, we use HttpClient.get() method to access JSON data from the server. In the HTTP GET method { responseType: 'json'} is optional, it is not mandatory to use in the method.

companydetails = "/api/companyDetails"; //API path

getFavEmployee(): Observable {
    return this.http.get(this.companydetails, { responseType: 'json' });
}

After the call service method from the component, we will use the subscribe method to subscribe observable data. Because the user can not read directly observable data in the component.

constructor(private employeeService: EmployeeService, private formBuilder: FormBuilder) {}   
   getFavEmployee() {
	this.employeeService.getFavEmployee().subscribe(
	  (data: any) => this.favEmployee = data['enployee']
	);
  }

Interface

We use an interface for typechecking responses. If we want to check the data type in the return response, We can create an interface and define the data type.

export interface Employee {
   id: number;
   name: string;
   department: string;
   profile: string;
}

After calling the getFavEmployee() method from the employee component, we get observable data from the server. So we display company employee data in components with the help of the subscribe method. In a component without a subscribe call, the server will not hit.

<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Department</th>
    <th>Profile</th>
  </tr>
  <tr *ngFor="let emp of favEmployee">
     <td>{{emp.id}}</td>
     <td>{{emp.name}}</td>
     <td>{{emp.department}}</td>
     <td>{{emp.profile}}</td>
  </tr>
</table>

By HttpClient.get() requesting Text Data

If we want to access text data from API, we need to use responseType: text in the GET method. The GET method, the second parameter is optional, In which place do we put responseType: text

//Text data
let welcomeMsg = "Welcome to webrecto.com";

In Angular application, now we uses hHttpClient.get() with responseType: text

textUrl = "/api/message";
getTextMsg(): Observable {
   return this.http.get(this.textUrl, { responseType: 'text' });
}

After a successful request, the API returns an observable response. We have two options to read observable data. One uses use async pipe and the other uses the .subscribe() method. Here we are using an async pipe to display text message data.

getTextMsg() {
   this.obsTextMsg = this.employeeService.getTextMsg();
   this.employeeService.getTextMsg().subscribe(
      (msg: string) => console.log(msg)
   );
}
<h3 *ngIf="obsTextMsg | async as message" > {{ message }} </h3>

Output:
Welcome to webrecto.com

Use a parameter to filter data from API

We can find filter data from the server to pass some conditional parameters with the endpoint. In an angular REST API, path parameters can be used to filter data by encoding the filtering conditions as part of the URL path.

// service file
   empUrl = "/api/employee";
     filterEmployee(name: string, department: string): Observable {
        let httpHeaders = new HttpHeaders()
            .set('Accept', 'application/json');
        return this.http.get(this.empUrl + '?name=' + name + '&department=' + department, {
            headers: httpHeaders,
            responseType: 'json'
        });
    }
     

In the code, I am using employee details data in JSON format for display in the component.. I am passing the two parameters in REST API, one is the employee name and the other is a department parameter. After execution, it returns filter employee data to display in the component.

// component
filterEmployee(name: string, department: string) {
 this.employeeService.filterEmployee(name, department)
  .subscribe((data: Employee[]) => this.employee = data);
 }

From the component, I am taking two inputs from the select dropdown and sending them to the service through the component method. In a component, I get matched data from the server, which parameter is passed from API.

RxJs retry() Error Handling Operator

RxJs retry() operator is imported from rxjs/operators library. This operator is an error handling operator. The operator accepts the number argument and returns an observable.

import { retry } from 'rxjs/operators';

RxJs retry() operator is used to handle and take care of retrying back on the source observable. if there is an error and the retry will be done based on the input count given. If we pass the argument as retry(2) then the request will be retried 2 times.

In example, we are using retry() operator for error handling.

import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
getCompanyName() {
 this.employeeService.getCompanyName().pipe(
   retry(2)
 ).subscribe(
   (data: CompanyInfo) => {
      this.favEmp = data;
      console.log(this.favEmp.employee);
   },
   (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
         //A client-side or network error occurred.				 
         console.log('An error occurred:', err.error.message);
      } else {
         //Backend returns unsuccessful response codes such as 404, 500 etc.
         console.log('Backend returned status code: ', err.status);
         console.log('Response body:', err.error);
      }
   }
  );
 }
}

Complete Example

employee.ts

// Interface
export interface Employee {
   id: number;
   name: string;
   department: string;
   profile: string;
}

employee.service.ts

// service file
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Employee } from './employee';
import { CompanyInfo } from './company';

@Injectable({
    providedIn: 'root'
})
export class EmployeeService {

    constructor(private http: HttpClient) { }

    textUrl = "/api/message";
    getTextMsg(): Observable {
        return this.http.get(this.textUrl, { responseType: 'text' });
    }

    empUrl = "/api/employee";

    getEmployee(): Observable {
        return this.http.get(this.empUrl);
    }

    filterEmployee(name: string, department: string): Observable {
        let httpHeaders = new HttpHeaders()
            .set('Accept', 'application/json');
        return this.http.get(this.empUrl + '?name=' + name + '&department=' + department, {
            headers: httpHeaders,
            responseType: 'json'
        });
    }

    companydetails = "/api/companyDetails";

    getFavEmployee(): Observable {
        return this.http.get(this.companydetails, { responseType: 'json' });
    }
    
    getCompanyName(): Observable {
        return this.http.get(this.companydetails, { responseType: 'json' });
    }
}

employee.component.ts

// component
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { FormBuilder, FormControl } from '@angular/forms';
import { retry } from 'rxjs/operators';
import { EmployeeService } from './employee.service';
import { Employee } from './employee';
import { CompanyInfo } from './company';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html'
})
export class EmployeeComponent implements OnInit {
   obsTextMsg: Observable;
   obsEmployee: Observable;
   employee: Employee[] = [];
   favEmployee: Employee[] = [];
   favEmp = {} as CompanyInfo;
   CompanyInfo = {} as CompanyInfo;

names = [
      { name: 'Ramesh' },
      { name: 'Shantosh' },
      { name: 'Ashutosh' },
      { name: 'Shobhit' }
];
departments = [
      { department: 'Angular Team' },
      { department: 'React Team' },
      { department: 'Java Team' },
      { department: 'UI Team' }
];
	
constructor(private employeeService: EmployeeService,
      private formBuilder: FormBuilder) {
      this.obsTextMsg = this.employeeService.getTextMsg();
      this.obsEmployee = this.employeeService.getEmployee();
}

ngOnInit() {
   this.getTextMsg();
   this.getEmployee();
   this.getFavEmployee();
   this.getCompanyName();
   this.employeeForm = this.formBuilder.group({
      name: '',
      department: ''
   });
}
employeeForm = this.formBuilder.group({
   name: [''],
   department: ['']
});

getName() {
   return this.employeeForm.get('name') as FormControl;
}
getDepartment() {
   return this.employeeForm.get('department') as FormControl;
}

onFormSubmit() {
   let name = this.getName().value;
   let department = this.getDepartment().value;
   this.filterEmployee(name, department);
}

getTextMsg() {
   this.obsTextMsg = this.employeeService.getTextMsg();
   this.employeeService.getTextMsg().subscribe(
      (msg: string) => console.log(msg)
   );
}
getEmployee() {
   this.obsEmployee = this.employeeService.getEmployee();
}
filterEmployee(name: string, department: string) {
   this.employeeService.filterEmployee(name, department)
      .subscribe((data: Employee[]) => this.employee = data);
}
getFavEmployee() {
   this.employeeService.getFavEmployee().subscribe(
      (data: any) => this.favEmployee = data['enployee']
   );
}
getCompanyName() {
this.employeeService.getCompanyName().pipe(
   retry(2) // Error handling
).subscribe(
   (data: CompanyInfo) => {
      this.favEmp = data;
      console.log(this.favEmp.employee);
   },
   (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
         //A client-side or network error occurred.				 
         console.log('An error occurred:', err.error.message);
      } else {
         //Backend returns unsuccessful response codes such as 404, 500 etc.
         console.log('Backend returned status code: ', err.status);
         console.log('Response body:', err.error);
      }
   }
  );
 }
}

employee.component.html

<h3 *ngIf="obsTextMsg | async as message"> {{ message }} </h3>

<h3>Employee Details</h3>
<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Department</th>
    <th>Profile</th>
  </tr>
  <tr *ngFor="let emp of obsEmployee | async">
     <td>{{emp.id}}</td>
     <td>{{emp.name}}</td>
     <td>{{emp.department}}</td>
     <td>{{emp.profile}}</td>
  </tr>
</table>

<h3>Filter Employee</h3>
<form [formGroup]="employeeForm" (ngSubmit)="onFormSubmit()">
  Select Name:
  <select formControlName="name">
    <option *ngFor="let name of names" [ngValue]="name.name">
      {{ name.name }}
    </option>
  </select>
  Select Department:
  <select formControlName="department">
    <option *ngFor="let dep of departments" [ngValue]="dep.department">
      {{ dep.department }}
    </option>
  </select>
  <button>SUBMIT</button>
</form>
Result:

<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Department</th>
    <th>Profile</th>
  </tr>
  <tr *ngFor="let emp of employee">
     <td>{{emp.id}}</td>
     <td>{{emp.name}}</td>
     <td>{{emp.department}}</td>
     <td>{{emp.profile}}</td>
  </tr>
</table>

<h3>Favorite Employee</h3>
<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Department</th>
    <th>Profile</th>
  </tr>
  <tr *ngFor="let emp of favEmployee">
     <td>{{emp.id}}</td>
     <td>{{emp.name}}</td>
     <td>{{emp.department}}</td>
     <td>{{emp.profile}}</td>
  </tr>
</table>


<h3>Company Details</h3>
<div *ngIf="favEmp">
  Company Id: <b>{{favEmp.companyId}}</b>, Company Name: <b>{{favEmp.companyName}}</b>
  <tr *ngFor="let emp of favEmp.employee">
    <td>{{emp.id}}</td>
    <td>{{emp.name}}</td>
    <td>{{emp.department}}</td>
    <td>{{emp.profile}}</td>
 </tr>
</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
   <app-employee></app-employee>
`
})
export class AppComponent { 
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee.component';

//For InMemory testing
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { TestData } from './test-data';

@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        ReactiveFormsModule,
        InMemoryWebApiModule.forRoot(TestData)
    ],
    declarations: [
        AppComponent,
        EmployeeComponent
    ],
    providers: [
    ],
    bootstrap: [
        AppComponent
    ]
})
export class AppModule { }

Find the print screen of the output

Angular HttpClient get Example

Reference

Download Source Code