npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@umardraz/ngx-http-retry

v1.0.5

Published

Angular HTTP client wrapper with configurable retry logic.

Downloads

69

Readme

NgxHttpRetryService

npm version npm downloads license

An Angular service that provides HTTP methods (GET, POST, PUT, DELETE) with built-in retry logic using RxJS's retry operator.

Table of Contents

Installation

Install the package via npm:

npm install ngx-http-retry

Usage

Importing the Service

Import NgxHttpRetryService into your Angular component or service:

import { NgxHttpRetryService } from 'ngx-http-retry';

@Component({
  // ...
})
export class YourComponent {
  constructor(private httpRetryService: NgxHttpRetryService) {}
}

Available Methods

The service provides the following methods, which mirror Angular's HttpClient methods but include retry logic:

  • get<T>(url: string, options?: any, retries?: number, delayMs?: number): Observable<T>
  • post<T>(url: string, body: any, options?: any, retries?: number, delayMs?: number): Observable<T>
  • put<T>(url: string, body: any, options?: any, retries?: number, delayMs?: number): Observable<T>
  • delete<T>(url: string, options?: any, retries?: number, delayMs?: number): Observable<T>

get

Performs a GET request with retry logic.

Parameters:

  • url: string - The endpoint URL.
  • options?: any - Optional HTTP options.
  • retries?: number - Number of retry attempts (default: 3).
  • delayMs?: number - Delay between retries in milliseconds (default: 1000).

Returns:

  • Observable<T> - An observable of the response.

Example:

this.httpRetryService.get<User[]>('https://api.example.com/users')
  .subscribe(
    users => console.log(users),
    error => console.error('Request failed', error)
  );

post

Performs a POST request with retry logic.

Parameters:

  • url: string - The endpoint URL.
  • body: any - The payload to send.
  • options?: any - Optional HTTP options.
  • retries?: number - Number of retry attempts (default: 3).
  • delayMs?: number - Delay between retries in milliseconds (default: 1000).

Returns:

  • Observable<T> - An observable of the response.

Example:

const payload = { name: 'John Doe', email: '[email protected]' };
this.httpRetryService.post<User>('https://api.example.com/users', payload)
  .subscribe(
    user => console.log('User created:', user),
    error => console.error('Request failed', error)
  );

put

Performs a PUT request with retry logic.

Parameters:

  • url: string - The endpoint URL.
  • body: any - The payload to update.
  • options?: any - Optional HTTP options.
  • retries?: number - Number of retry attempts (default: 3).
  • delayMs?: number - Delay between retries in milliseconds (default: 1000).

Returns:

  • Observable<T> - An observable of the response.

Example:

const updatedData = { name: 'Jane Doe' };
this.httpRetryService.put<User>('https://api.example.com/users/1', updatedData)
  .subscribe(
    user => console.log('User updated:', user),
    error => console.error('Request failed', error)
  );

delete

Performs a DELETE request with retry logic.

Parameters:

  • url: string - The endpoint URL.
  • options?: any - Optional HTTP options.
  • retries?: number - Number of retry attempts (default: 3).
  • delayMs?: number - Delay between retries in milliseconds (default: 1000).

Returns:

  • Observable<T> - An observable of the response.

Example:

this.httpRetryService.delete<void>('https://api.example.com/users/1')
  .subscribe(
    () => console.log('User deleted'),
    error => console.error('Request failed', error)
  );

Customizing Retries

Customize the number of retries and delay between retries:

this.httpRetryService.get<User[]>('https://api.example.com/users', {}, 5, 2000)
  .subscribe(
    users => console.log(users),
    error => console.error('Request failed after retries', error)
  );
  • Retries: 5
  • Delay: 2000 milliseconds

Retry Strategy

The retry logic uses RxJS's retry operator with a custom strategy.

private retryStrategy<T>(retries: number, delayMs: number) {
  return retry<T>({
    count: retries,
    delay: (error: HttpErrorResponse, retryCount: number) => {
      if (this.isNonRetryableError(error)) {
        throw error;
      } else {
        console.warn(`Retry attempt #${retryCount}`);
        return timer(delayMs);
      }
    },
  });
}

Non-Retryable Errors

By default, the following HTTP errors are not retried:

  • Client-side errors (4xx), except for 408 Request Timeout.
private isNonRetryableError(error: HttpErrorResponse): boolean {
  return error.status >= 400 && error.status < 500 && error.status !== 408;
}

Exponential Backoff

To implement exponential backoff, modify the retryStrategy:

private retryStrategy<T>(retries: number, delayMs: number) {
  return retry<T>({
    count: retries,
    delay: (error: HttpErrorResponse, retryCount: number) => {
      if (this.isNonRetryableError(error)) {
        throw error;
      } else {
        const backoffDelay = delayMs * Math.pow(2, retryCount - 1);
        console.warn(`Retry attempt #${retryCount} after ${backoffDelay}ms`);
        return timer(backoffDelay);
      }
    },
  });
}

Custom Retry Conditions

Customize retry conditions based on specific error codes or responses:

private retryStrategy<T>(retries: number, delayMs: number) {
  return retry<T>({
    count: retries,
    delay: (error: HttpErrorResponse, retryCount: number) => {
      if (this.isNonRetryableError(error) || retryCount > retries) {
        throw error;
      } else if (error.status === 500) {
        // Immediate retry for server errors
        return timer(0);
      } else {
        return timer(delayMs);
      }
    },
  });
}

Error Handling

Handle errors where you consume the service:

this.httpRetryService.get<User[]>('https://api.example.com/users')
  .subscribe(
    users => {
      // Successful response
    },
    error => {
      // Error after all retries
      console.error('Request failed', error);
    }
  );

Extending the Service

For extensive customization, extend NgxHttpRetryService:

@Injectable({
  providedIn: 'root',
})
export class CustomHttpRetryService extends NgxHttpRetryService {
  protected isNonRetryableError(error: HttpErrorResponse): boolean {
    // Custom logic (e.g., don't retry on 404)
    return error.status === 404;
  }
}

Use CustomHttpRetryService in your components:

constructor(private httpRetryService: CustomHttpRetryService) {}

FAQs

Does this service support Angular Universal (Server-Side Rendering)?

Yes, it is compatible with Angular Universal.

How is this different from using HttpClient directly?

NgxHttpRetryService wraps HttpClient methods and adds configurable retry logic.

Can I use this service for file uploads or downloads?

Yes, any HTTP request supported by HttpClient can be used.

Does it support HTTP interceptors?

Yes, any interceptors configured with HttpClient are applied.

Contributing

Contributions are welcome! Please submit issues or pull requests on GitHub.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Author

Umar Draz

Changelog

v1.0.0

  • Initial release with GET, POST, PUT, DELETE methods and retry logic.