To implement retry logic, Angular provides a powerful operator called retry from the RxJS library. You can specify how many times to try a failed request with this operator.
Basic Retry Implementation
Here’s a simple example of how to use the retry operator in your service:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, retry } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ApiService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://api.example.com/data').pipe(
retry(2), // Retry the request up to 2 times
catchError(this.handleError) // Handle errors
);
}
private handleError(error: any) {
console.error('An error occurred:', error);
return throwError('Something went wrong; please try again later.');
}
}