Handling HTTP Requests with RxJS in Angular
🔗 Handling HTTP Requests with RxJS in Angular
Managing HTTP requests efficiently is a crucial part of any Angular application. With RxJS, we can handle API calls reactively, ensuring better performance and error handling.
📋 Topics Covered
- Using HttpClient with RxJS
- Managing API calls with
switchMap - Retrying failed requests with
retry
1️⃣ Using HttpClient with RxJS
The HttpClient module returns an Observable, which makes it ideal for use with RxJS operators.
Importing HttpClientModule
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientModule]
})
export class AppModule {}
DataService Example
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
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(this.apiUrl);
}
}
Using in Component
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-posts',
template: `<div *ngFor="let post of posts">{{ post.title }}</div>`
})
export class PostsComponent implements OnInit {
posts: any[] = [];
constructor(private dataService: DataService) {}
ngOnInit(): void {
this.dataService.getPosts().subscribe(data => {
this.posts = data;
});
}
}
2️⃣ Managing API Calls with switchMap
switchMap is perfect for chaining or cancelling in-flight API calls, ensuring only the latest result is processed.
AuthService Example
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class AuthService {
private loginUrl = 'https://api.example.com/login';
private userDetailsUrl = 'https://api.example.com/user/';
constructor(private http: HttpClient) {}
login(credentials: { username: string; password: string }): Observable {
return this.http.post<{ userId: number }>(this.loginUrl, credentials).pipe(
switchMap(response => this.http.get(`${this.userDetailsUrl}${response.userId}`))
);
}
}
🔍 Explanation
- Login API returns user ID.
switchMaptriggers a second request to fetch user details.- Any previous in-flight request is canceled.
3️⃣ Retrying Failed Requests with retry
Use retry to handle transient errors like network issues.
Retry Example in DataService
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
getPosts(): Observable<any> {
return this.http.get(this.apiUrl).pipe(
retry(3),
catchError(error => {
console.error('Request failed after 3 retries', error);
throw error;
})
);
}
}
✨ Why Use retry?
- Handles temporary network failures automatically.
- Improves reliability without showing errors to users.
- Reduces unnecessary alerts and interruptions.
✅ Summary Table
| RxJS Operator | Use Case |
|---|---|
HttpClient |
Simple API requests |
switchMap |
Chained or dependent API calls |
retry |
Retry failed requests automatically |
RxJS makes handling HTTP requests in Angular more reactive, efficient, and resilient. Mastering operators like switchMap and retry helps build user-friendly, fault-tolerant apps.
Comments
Post a Comment