Tips on continuously making calls to a backend API until receiving a successful response with status code 200

While working on my Angular project, I have encountered a situation where I need to make calls to a backend API. If the response is not 200 OK, I have to keep calling the API every 30 seconds until I receive a successful response.

In Angular, I usually call a backend API using the following format:

this.productServices.onProductBuy(product_id).subscribe(response => {
    console.log(response)
});

The onProductBuy() function contains the code for making a simple GET request to the API.

If I do not receive a HTTP 200 response from this onProductBuy API, I will continue calling it until I get the desired 200 status.

Answer №1

Here's a solution you can try:

this.productServices.onProductBuy(product_id).pipe(
  retry({
    delay: 30 * 1000
  } as any)
).subscribe(response => {
  console.log(response)
});

This will attempt to retry infinitely and introduce a 30-second delay between retries. It appears that the type definition for retry is not functioning correctly in the version I am using, hence the need for as any.

However, looking at the source code, it is evident that retry actually accepts an object with a delay property:

export interface RetryConfig {
  /**
   * The maximum number of times to retry. If `count` is omitted, `retry` will try to
   * resubscribe on errors infinite number of times.
   */
  count?: number;
  /**
   * The number of milliseconds to delay before retrying, OR a function to
   * return a notifier for delaying. If a function is given, that function should
   * return a notifier that, when it emits will retry the source. If the notifier
   * completes _without_ emitting, the resulting observable will complete without error,
   * if the notifier errors, the error will be pushed to the result.
   */
  delay?: number | ((error: any, retryCount: number) => ObservableInput<any>);
  /**
   * Whether or not to reset the retry counter when the retried subscription
   * emits its first value.
   */
  resetOnSuccess?: boolean;
}

export function retry<T>(count?: number): MonoTypeOperatorFunction<T>;
export function retry<T>(config: RetryConfig): MonoTypeOperatorFunction<T>;

Answer №2

If you're looking to handle retries in your code, consider utilizing the rxjs retry method:

this.productServices.onProductBuy(product_id)
  .pipe(retry(2)) // <-- Give it a shot here
  .subscribe(response => {
    console.log(response)
  });

The above example will retry twice. To retry indefinitely, simply omit the number parameter:

this.productServices.onProductBuy(product_id)
  .pipe(retry()) // <-- Try this instead
  .subscribe(response => {
    console.log(response)
  });

Remember to be cautious of potential memory leaks when dealing with subscriptions.

Answer №3

Alright!

Personally, I believe it would be best to handle this in the backend framework. However, if you insist on solving it through the Angular side of the application, here is my proposed solution (without using retry as it can sometimes be problematic as others have already mentioned):

  1. Start by defining a Subject in the ProductService Class:

    public onProductBySubject = new Subject();

  2. Create a method in your component.ts file (if not already defined) to call the necessary method from the service class:

    public justAnExample() { this.productServices.onProductBuy(product_id).subscribe(response => {

    if(response.code !== 200){ setTimeOut(this.productServices.onProductBySubject.next(true),30000); } console.log(response) }); }

  3. In the ngOnInit() lifecycle hook function, subscribe to the Subject:

    this.mysubscription = this.productServices.onProductBySubject.subscribe(value=>{ if(value) this.justAnExample(); });

  4. Don't forget to unsubscribe 'mysubscription' in the ngOnDestroy() lifecycle hook function.

If this solution helps, let me know and consider upvoting my answer to help others as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Oops! Angular2 couldn't find a provider for HttpHandler

I have been working on implementing HttpCache through an interceptor. Below is the code snippet for caching-interceptor.service.ts: import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http' import ...

registering a back button action in Ionic2 for multiple pages

Currently, I am in the process of developing my Ionic2 app and have encountered a dilemma regarding the functionality of registerBackButtonAction. On one page, let's call it pageA, I have implemented this function and everything is functioning as exp ...

Angular 2: The *ngFor directive is unable to locate a suitable differing framework

Below is the code for client.service.ts clients: Client[]; getClientList() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token&apo ...

Choosing between running a single unit test or multiple tests using Karma toggle switch

Currently, I am working on writing unit tests using the Karma/Jasmine combination and I'm curious if there's a way to target a specific spec file for testing instead of running all the spec files in the files array defined in the karma.conf.js fi ...

Changes in tabs are discarded when switching between them within Material UI Tabs

I have been experiencing an issue with the Material UI tab component where changes made in tabs are discarded when switching between them. It seems that after switching, the tabs are rendered again from scratch. For example, let's say I have a textFie ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...

Can you modify a specific column in a table using mat-table in Angular material?

For my project, I am utilizing Angular Material's table to present data in a tabular format. However, due to a new requirement, I now need to enable in-line editing for the last 2 columns alongside highlighting another column when the user clicks on t ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

Out with TSLint, in with ESLint: Upgrading our code quality tool

I have been working on a project in Angular 10 that was recently upgraded to Angular 12. With the upgrade, TSLint is no longer used in Angular 12, but remnants of it still exist in the project, such as the tslint.json file and associated packages. How ca ...

Having trouble getting Angular's ngClass directive to work correctly when applying multiple conditions

Struggling to make multiple conditions work with [ngClass] Check out a.component.html <div class="version-content" *ngFor="let version of versions; let lastVersion = last" [ngClass]="(version.isComingSoon === true) ? 'dashed': 'solid"> ...

A complete guide on utilizing *ngFor in Angular to display data rows

I am facing an issue with using *ngFor to create new "rows" for adding new categories dynamically. Although there are no errors displayed when I run the program, the intended functionality is not achieved. I have tried making some modifications but it see ...

Avoid using dot notation with objects and instead use `const` for declaring variables for more

interface obj { bar: string } function randomFunction() { let foo: obj = { bar: "" } foo.bar = "hip" } let snack: obj = { bar: "" } snack.bar = "hop" Upon transcompiling, a warning from tslint pops up: Identifier 'foo' is never reassi ...

Error encountered when attempting to open PDF documents located in the ./../../../assets/pdf/file.pdf directory. Route matching failed, resulting in inability to access the

In my Angular application, I have stored the PDF file under the assets/pdf directory. Here is the code snippet: <div class="container-fluid mt-2 mb-2"> <a target="_blank" href="./../../../assets/pdf/MSW - Transition Briefing Slides v1.1.pdf"& ...

Encountering an issue with the 'createObjectURL' function in URL, resulting in overload resolution failure when using npm file-saver

While working on my angular app, I encountered a situation where I needed to download user details uploaded as a Word document to my local machine using the angular app. Successfully, I was able to upload and save this data to my database, getting its byte ...

Ways to protect your ExpressJS RESTful API from unauthorized access

Is it possible to enhance security for an expressjs RESTful API so that only a react native app and react website have access? For example, the server runs on port 8000, the react native app is on port 3000, and the website on port 5000. It’s desired th ...

ESLint not functioning properly on TypeScript (.ts and .tsx) files within Visual Studio Code

After installing the ESLint extension in VSC, I encountered an issue where it was no longer working on the fly for my React project when I introduced Typescript. In the root of my project, I have a .eslintrc file with the following configuration: { "pa ...

Turning a file path into a complete URL using Express

I am currently using Node.js with Express for my backend code. When I upload pictures, they are saved in a folder and the absolute path is stored in the database. My question is how can I convert this absolute path into a valid URL including the hostname ...

Utilizing React with Typescript: A guide to working with Context

I have a super easy app snippet like import React, { createContext } from 'react'; import { render } from 'react-dom'; import './style.css'; interface IAppContext { name: string; age: number; country: string; } const A ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...

Create and save data to a local file using Angular service

I am facing an issue with my Angular service: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { person } from '../interfaces/iperson ...