In Angular, the HttpClient module is used to make HTTP requests to backend services. It simplifies communication with APIs, allowing developers to interact with RESTful services, send and receive data, and handle responses effectively.
This article will guide you through setting up HttpClient, making various types of HTTP requests, and handling responses in an Angular application.
Prerequisites
Setting Up HttpClient
To use HttpClient, you need to import and configure it within your Angular application.
Importing HttpClientModule
Start by importing HttpClientModule in your feature module or in the root module if you're using a single module setup.
Syntax:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
// other imports
],
// other configurations
})
export class FeatureModule { }
This enables your Angular app to use HttpClient for making HTTP requests.
Making HTTP Requests
After setting up HttpClientModule, you can start making HTTP requests by injecting HttpClient into your services.
Injecting HttpClient
To inject HttpClient, first, create a service where you will define your HTTP requests:
Step 1. Generate the Service:
ng generate service data
Step 2. Inject HttpClient in the Service:
Syntax:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https://api.example.com/data'; // Replace with your API URL
constructor(private http: HttpClient) { }
}
Step 3. Making HTTP Requests
Now that HttpClient is injected, you can define methods to perform different types of HTTP requests:
A GET request retrieves data from the server.
Syntax:
getData(): Observable < any > {
return this.http.get(this.apiUrl);
}
A POST request sends data to the server to create a new resource.
Syntax:
postData(payload: any): Observable < any > {
return this.http.post(this.apiUrl, payload);
}
A PUT request updates an existing resource on the server.
Syntax:
updateData(id: number, payload: any): Observable < any > {
return this.http.put(`${this.apiUrl}/${id}`, payload);
}
A DELETE request removes a resource from the server.
Syntax:
deleteData(id: number): Observable < any > {
return this.http.delete(`${this.apiUrl}/${id}`);
}
Handling Response
Angular's HttpClient returns an Observable, which allows you to handle the asynchronous nature of HTTP requests gracefully.
Observables
Observables are used to handle asynchronous data streams. When you make an HTTP request, the HttpClient returns an Observable of the HTTP response.
Here’s an example of how to subscribe to an Observable:
Syntax:
this.dataService.getData().subscribe(
response => {
console.log('Response:', response);
},
error => {
console.error('Error:', error);
}
);
Error Handling
Error handling in Angular is straightforward. You can catch errors using the catchError operator from RxJS.
Here’s how you can handle errors in your HTTP requests:
Syntax:
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
getData(): Observable < any > {
return this.http.get(this.apiUrl).pipe(
catchError(error => {
console.error('Error occurred:', error);
return throwError(error);
})
);
}
Basic Syntax
To use HttpClient, you need to import it from @angular/common/http and inject it into your service or component. Here’s the basic syntax:
Syntax:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
Explanation:
- Importing HttpClient: Import HttpClient from @angular/common/http to use it in your Angular service or component.
- Dependency Injection: Inject HttpClient in the constructor of your service or component to make HTTP requests.
Making GET Requests
To perform a GET request:
Syntax:
this.http.get('https://api.example.com/data').subscribe(response => {
console.log(response);
});
Explanation:
- Usage: Ideal for retrieving data from a server.
- Example: Fetching a list of items or user data.
Making POST Requests
To perform a POST request:
Syntax:
this.http.post('https://api.example.com/data', { key: 'value' }).subscribe(response => {
console.log(response);
});
Explanation:
- Usage: Used to send data to a server, such as submitting a form or adding new data.
- Example: Creating a new user or submitting a form
Handling Responses
To handle responses, including errors:
Syntax:
this.http.get('https://api.example.com/data').subscribe(
response => console.log(response),
error => console.error('Error:', error)
);
Explanation:
- Success: Process the response data in the next callback.
- Error: Handle errors in the error callback to manage failed requests.
Steps to Create Application
Step 1: Install Angular CLI
npm install -g @angular/cli
Step 2: Create a New Angular Project
ng new httpClient-Angular-app
cd httpClient-Angular-app
Step 3: Install HttpClientModule
npm install @angular/common
Step 4: Create a Service
ng generate service services/data
Step 5: Use HttpClient in Service
Syntax:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://api.example.com/data');
}
}
Step 6: Inject Service into Component
Use the service in your component.
Syntax:
import { Component, OnInit } from '@angular/core';
import { DataService } from './services/data.service';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
data: any;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.data = data;
});
}
}
Step 7: Provider for httpClient : (app.config.ts)
Syntax:
//src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http'; // Import HttpClientModule
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient(),]
};
Dependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.12",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Folder Structure
Folder StructureExample: Here’s a complete example of using HttpClient in a simple Angular application:
App Component:
Below mentioned is the App Component having app.component.html, app.config.ts and app.component.ts file. In the example, HTML fie stores the data to be displayed on browser whereas app.component.ts file used to bind data with HTML.
HTML
<!-- src/app/app.component.html !-->
<h1>HttpClient angular app example</h1>
<h2>Response Data for GET request</h2>
<div>
<p>id: {{data.id}}</p>
<p> Title: {{data.title}}</p>
<p>Body : {{data.body}}</p>
<p>User Id: {{data.userId}}</p>
</div>
<p>
<button (click)="sendPostRequest()">
Send post request
</button>
</p>
<h2>
Reponse from the server for POST request:
</h2>
<div>
<p>
Title : {{PostDataResponse.title}}
</p>
<p>
Body : {{PostDataResponse.body}}
</p>
<p>
User Id : {{PostDataResponse.userId}}
</p>
</div>
<router-outlet />
JavaScript
//src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http'; // Import HttpClientModule
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient(),]
};
JavaScript
//src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { DataService } from './services/data.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
data: any;
// Example data to be sent in POST request
PostdataExample = {
title: 'GeeksforGeeks',
body: 'This is a post request for test',
userId: 1,
};
PostDataResponse: any;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.data = data;
});
}
// Method to send POST request
sendPostRequest() {
this.dataService.postData(this.PostdataExample).subscribe(
response => {
this.PostDataResponse = response;
console.log('Response from server:', response);
},
error => {
console.error('Error occurred:', error);
}
);
}
}
Service(services/data.service.ts)
Below mentioned is the code example of data service which is using an API to get data.
JavaScript
//src/app/services/data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
getData() {
return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
}
// Method to perform a POST request
postData(payload: any): Observable<any> {
return this.http.post(this.apiUrl, payload);
}
}
Note : We are using public API for testing purpose(https://catfact.ninja/fact').
Output
How To Use HttpClient in Angular
Similar Reads
HTTP Interceptor use-cases in Angular In Angular, HTTP interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses at a centralized location. They act as middleware, sitting between the applicationâs HTTP client (typically the built-in HttpClient module) and the server.In this article, we will
6 min read
How to Use Loading in Interceptor? - Angular 17 In Angular applications, HTTP interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses. One common use case for interceptors is to display a loading indicator to the user while an HTTP request is in progress. This improves the user experience by providi
5 min read
How to Use the Async Pipe in Angular? The AsyncPipe in Angular is a powerful and convenient tool used to handle asynchronous data streams such as observables and promises directly in the component template. It automatically subscribes to observables, renders their values, and updates the view when new data is emitted. This removes the n
3 min read
How to use services with HTTP methods in Angular v17? In Angular 17, services play an important role in managing HTTP requests to backend servers. By encapsulating HTTP logic within services, you can maintain clean, modular, and testable code. In this article, we'll explore how to use services to handle HTTP requests effectively in Angular 17 applicati
3 min read
HTTP Interceptors in Angular In Angular, HTTP interceptors are a powerful feature that allows you to intercept and modify HTTP requests and responses at a centralized location. They act as middleware, sitting between the application's HTTP client (typically the built-in HttpClient module) and the server. What is an HTTP Interce
5 min read
How to make an http call in angular Angular, with its robust framework and extensive ecosystem, offers you powerful tools for building modern web applications. One such tool is the HttpClient module, which provides a seamless way to make HTTP calls and interact with RESTful APIs or backend services. In this article, we'll explore maki
3 min read
How to send REST response to html in Angular ? In this article, we will see how to send API responses using HttpClient Module to an HTML using Angular, along with understanding the basic implementation through the examples.Angular is a JavaScript framework through which we can create reactive single-page web applications. For implementation, we
3 min read
How To Use @Injectable Decorator In Angular? In Angular, the @Injectable decorator is used to mark a class as available for dependency injection. This allows Angular to create and manage instances of this class and inject it into other components, services, or other classes.In this article, we will see how to use the @Injectable decorator in a
3 min read
Make HTTP requests in Angular? In Angular, making HTTP requests involves communicating with a server to fetch or send data over the internet. It's like asking for information from a website or sending information to it. Angular provides a built-in module called HttpClientModule, which simplifies the process of making HTTP request
4 min read
AngularJS Fetch Data From API using HttpClient There is some data in the API and our task here is to fetch data from that API using HTTP and display it. In this article, we will use a case where the API contains employee details which we will fetch. The API is a fake API in which data is stored in the form of a JSON (Key: Value) pair. API stands
4 min read