Most front-end applications need to communicate with a server over the HTTP protocol, in order to download or upload data and access other back-end services.
The HttpClientModule in Angular is a built-in module that allows you to make HTTP requests and handle responses in your Angular applications. It provides a convenient way to communicate with servers, retrieve data, and perform CRUD (Create, Read, Update, Delete) operations over HTTP.
To use the HttpClientModule, you need to import it into your Angular module. Typically, this is done in the root module (e.g., AppModule) or a feature module where you want to use HTTP functionality. Here’s an example of importing the HttpClientModule:
import { NgModule } from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import { HttpClientModule } from ‘@angular/common/http’;
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
a. The HttpClient service
Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http. It relies on the XMLHttpRequest interface exposed by browsers. The HttpClient service class is part of the HttpClientModule which is used to send HTTP requests and receive responses from a server. It simplifies the process of making HTTP requests and handling responses by providing a set of methods and features.
b. Importing the HttpClient service class
Once the HttpClientModule is imported, you can inject the HttpClient service into your Angular components or services using dependency injection. Angular will provide an instance of the service when it is requested.
import { Injectable } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
c. Using the HttpClient methods
The HttpClient service provides several methods for making different types of HTTP requests, including GET, POST, PUT, DELETE, and more. The most commonly used methods are get(), post(), put(), and delete(). The methods return observables that you can subscribe to in order to receive the response. Here are some commonly used methods:
- HttpClient.get()
Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received.
The get() method takes an argument i.e. the endpoint URL from which to fetch the data.
this.http.get(url).subscribe(data => {
// Handle the response
});
- HttpClient.post()
Apps often send data to a server with a POST request when submitting a form. The HttpClient.post() method takes a resource URL and a request body as parameters.
const body = { name: ‘John’, age: 30 };
this.http.post(url, body).subscribe(data => {
// Handle the response
});
- HttpClient.put()
An app can send PUT requests using the HTTP client service. The HttpClient.put() method replaces a resource with updated data.
const body = { name: ‘John’, age: 30 };
this.http.put(`${this.heroesUrl}/${id}`, body).subscribe(data => {
// Handle the response
});
- HttpClient.delete()
The application can delete a resource with the HttpClient.delete() method by passing the resource’s id in the request URL.
this.http.delete(`${this.heroesUrl}/${id}`).subscribe(data => {
// Handle the response
});
These are the ways we can use the HTTP methods for CRUD operations. Here, we are both calling the HTTP methods as well as handling the HTTP response at the same place. This may make our component look a bit clumsy sometimes. So, it is always a good practice to separate the HTTP calls and the response handling in different places in order to make our code easily readable. In order to achieve this, we place the HTTP calls separately in a service file and handle the response in our component.
Let us consider a small example where we will make a simple HTTP GET call to receive some data. As I have explained earlier, we need to place the HTTP call in a service as follows:
import { Injectable } from ‘@angular/core’;
import {HttpClient} from ‘@angular/common/http’;
@Injectable({
providedIn: ‘root’
})
export class MyService {
constructor(private http:HttpClient) { }
url = ‘https://abc.xyz’;
getCourses(){
return this.http.get(this.url);
}
}
Next, we will handle the response of the GET method in our component as follows:
import { Component } from ‘@angular/core’;
import { MyService } from ‘./my.service’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
courses:any;
constructor(private ms:MyService){
}
handleGetMethod(){
this.ms.getCourses().subscribe((res:any)=>{
this.courses = res;
});
}
}
Here, we are injecting the MyService and using its getCourses method which is returning an Observable. In the handleGetMethod, we are subscribing the Observable to access the response and accordingly we can handle the response as required.
More Pages
-
All in Edupoly
-
HTML Advanced Tutorial
-
Practice Coding Problems
-
Reference Links
-
Registration Page
-
Test books and Notes
-
Java Programming Questions
-
Job Postings
-
HTML Coding Projects and Practice Examples
-
Code Chanlleges
-
Demo Classes
-
Quizzes Test Your Self
-
Upcoming Batches
-
Interview Questions
-
Free Video Tutorials
-
Coding Example Programs
-
Video Courses
-
Mini Capstone Projects
-
Workhops
-
Corporate Trainings