Angular

Handling API Requests in Angular with HttpClient

Introduction

In modern web applications, interacting with APIs is a crucial aspect of fetching, sending, and manipulating data. Angular provides a powerful HttpClient module that simplifies HTTP requests and response handling. This blog will guide you through setting up and using HttpClient to perform API requests efficiently in an Angular application.

Setting Up HttpClient in Angular

Before using HttpClient, make sure you have imported the HttpClientModule in your Angular application.

Step 1: Import HttpClientModule

Add the following import to your app.module.ts:

import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [...],
imports: [
HttpClientModule, // Import HttpClientModule here
...
],
providers: [],
bootstrap: [...]
})
export class AppModule {}

Step 2: Inject HttpClient into a Service

It is a best practice to handle API calls within a dedicated service instead of components.

Create an Angular service using the CLI:

ng generate service api

Then, modify api.service.ts as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ApiService {
private baseUrl = 'https://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
// GET request
getPosts(): Observable<any> {
return this.http.get(`${this.baseUrl}/posts`);
}
// POST request
createPost(postData: any): Observable<any> {
return this.http.post(`${this.baseUrl}/posts`, postData);
}
// PUT request
updatePost(id: number, updatedData: any): Observable<any> {
return this.http.put(`${this.baseUrl}/posts/${id}`, updatedData);
}
// DELETE request
deletePost(id: number): Observable<any> {
return this.http.delete(`${this.baseUrl}/posts/${id}`);
}
}

Using the API Service in a Component

Now, let's use the ApiService inside a component to fetch and display data.

Step 1: Inject ApiService into a Component

Modify app.component.ts as follows:

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
constructor(private apiService: ApiService) {}
ngOnInit(): void {
this.fetchPosts();
}
fetchPosts(): void {
this.apiService.getPosts().subscribe(
(data) => {
this.posts = data;
},
(error) => {
console.error('Error fetching posts:', error);
}
);
}
}

Step 2: Display Data in Template

Modify app.component.html to display posts:

<h1>Posts</h1>
<ul>
<li *ngFor="let post of posts">
<strong>{{ post.title }}</strong>
<p>{{ post.body }}</p>
</li>
</ul>

Handling Errors and HTTP Interceptors

To handle errors gracefully, use RxJS’s catchError operator:

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
getPosts(): Observable<any> {
return this.http.get(`${this.baseUrl}/posts`).pipe(
catchError((error) => {
console.error('Error occurred:', error);
return throwError(error);
})
);
}

Using HTTP Interceptors

Interceptors allow you to modify HTTP requests before they are sent. Create an interceptor using:

ng generate service interceptor

Modify interceptor.service.ts:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class InterceptorService implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const clonedRequest = req.clone({
setHeaders: { Authorization: 'Bearer your-token-here' },
});
return next.handle(clonedRequest);
}
}

Register the interceptor in app.module.ts:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { InterceptorService } from './interceptor.service';
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true },
],

Conclusion

Handling API requests in Angular is seamless with HttpClient. By following best practices like using services, error handling, and interceptors, you can build efficient and secure web applications. Experiment with these features in your projects and optimize your API interactions!

Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.

Contact Us

0

Comment

228

Share

facebook
LinkedIn
Twitter
Mail
Angular

Related Center Of Excellence