HTTP Requests with HttpClient in Angular
How to Make HTTP Requests with HttpClient in Angular
With the rise of modern web development, the ability to communicate with APIs has become a vital component of your Angular application. Angular has a built-in and powerful service called HttpClient for making HTTP calls.
HttpClient provides out-of-the-box methods that make it easier to:
Retrieve data from an API
Send form data
Handle errors efficiently
In this guide, we will cover:
- How to configure and use HttpClient in Angular
- How to deal with API calls efficiently
- Separating out HTTP logic into a service
- Doing subscription logic inside a component
Getting Started with HttpClient in Angular
Step 1 — Import HttpClientModule
To start using HttpClient, you first need to import the HttpClientModule in your app module.
Add HttpClientModule to app.module.ts:
Now, you can use HttpClient in your Angular application.
To keep the code clean and maintainable, move the API calls to an Angular service.
Step 2: Setting Up a Data Service
Run the following command to generate a new service:
ng g s data
This will create a data.service.ts file. Open the file and add the following code:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
getPosts(): Observable<any[]> {
return this.http.get<any[]>(this.apiUrl);
}
}
Why Move API Calls to a Service?
Keeps components clean and focused only on UI logic
Encourages reusability of API calls
Makes unit testing easier
Step 3: Subscribing to the API in a Component
Now, we will use the service inside a component. Update app.component.ts to subscribe to the API response:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
posts: any[] = [];
constructor(private dataService: DataService) {}
ngOnInit(): void {
this.dataService.getPosts().subscribe(
(response) => {
this.posts = response;
},
(error) => {
console.error('API Error:', error);
}
);
}
}
What’s Happening Here?
- The ngOnInit() lifecycle hook ensures data is fetched when the component loads.
- The subscribe() method listens for the API response and updates the posts array.
Step 4: Displaying Data in the Template
Now, update app.component.html to display the blog posts dynamically:
<h2>Blog Posts</h2>
<ul>
<li *ngFor="let post of posts">
<strong>{{ post.title }}</strong>
<p>{{ post.body }}</p>
</li>
</ul>
This will dynamically render the fetched posts in a simple list format.
Handling API Errors with RxJS
To gracefully handle errors, update data.service.ts to use catchError from RxJS:
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
getPosts(): Observable<any[]> {
return this.http.get<any[]>(this.apiUrl).pipe(
catchError((error) => {
console.error('API Error:', error);
return throwError(() => new Error('Something went wrong!'));
})
);
}
Why Handle Errors?
Logs API failures
Provides better user experience with error messages
Prevents app crashes
Best Practices for HttpClient Usage
Move API logic to a service to keep components clean.
Use RxJS operators like catchError to handle errors.
Unsubscribe from observables when needed to prevent memory leaks.
Store API URLs in environment variables instead of hardcoding them.
By now, you should be familiar with how to make HTTP requests with HttpClient in Angular.