Angular allows you to set specific conditions for when a failed HTTP request should be retried, and you can also specify the number of attempts that should be

Within my angular application, I have a post request that needs to be retried based on the error message, but with a limit on the number of attempts.

Initially, I attempted the following approach:

public post(url, data) {
    this._http.post(url, data).pipe(
      retry(3),
      catchError((err: HttpErrorResponse) => {
        if (err.message === 'something') {
          return EMPTY;
        }
      }),
    )
  } 

Unfortunately, this method retries sending the failing request without considering the condition inside catchError.
I then considered using the retryWhen() operator, but I am unsure how to set the number of attempts that should be made.

Answer №1

Exploring RetryWhen Functionality

This implementation may not align perfectly with RxJS conventions, but it serves as a good entry point for those looking to grasp the concept before diving into more advanced stream manipulation techniques.

The retryWhen operator generates a stream of error values that can be manipulated in various ways, such as ignoring them altogether. In this scenario, we utilize defer to establish local state (a counter) and then monitor these errors to tally specific occurrences.

new Observable(observer => {
  observer.next(1);
  observer.error({message: "something"});
  return {unsubscribe: () => {/* Do Nothing*/}};
}).pipe(
  retryWhen(errors => defer(() => {
    let count = 0; // Initialize a unique state
    return errors.pipe(
      switchMap(err => {
        if (err.message === "something" && count < 3){
          count++;
          return of(null); 
        }
        return throwError(err);
      })
    )
  }))
).subscribe({
  next: v => console.log("Next: ", v),
  error: e => console.log("Error: ", e),
  complete: () => console.log("Complete")
});

This code snippet should produce the following output (Comments added for clarity):

Next: 1  // Initial emission before encountering an error
Next: 1  // Emission after first retry
Next: 1  // Emission after second retry
Next: 1  // Emission after third retry
Error: {"message":"something"} // Exceeded maximum retries, halting further attempts

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

Embrace a variety of HTML template options when setting up a ReactJS component

Can someone help me understand how to render a component with template HTML data in ReactJS? class Options extends React.Component { render() { const othList = []; [1, 2, 3, 4, 5].forEach((t) => { othList.push(t); ...

Integrating a bokeh chart within a Flask application

Upon accessing localhost:5002/simpleline via Flask, I was hoping for a straightforward bokeh plot. Instead, what I encountered was unexpected: ('', ' ') I have two essential files involved in this process. Firstly, the Python file: f ...

Is it possible for me to generate typing/declaration (.d.ts) and decorator metadata (.metadata.json) files with the help of @ngtools/webpack?

Currently, I am in the process of updating an Angular library to be compatible with AOT compilation. To achieve this, I have set up some gulp tasks using ngc. However, I am considering switching to @ngtools/webpack as it provides a more convenient way fo ...

Save the status of checkboxes in a JSON file using boolean values of true or false

When a user submits a form, I am retrieving the values of checkboxes and storing them as an array. The simplified form structure is as follows: <!-- gym_create.html - other input fields are omitted for brevity --> <form class="create-gym" role=" ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

AngularJS $q - pausing execution to synchronize all promises

I've encountered a challenge that I haven't been able to solve through online searches. In my project, I am using a library for selecting items and performing custom modifications through callback functions. However, I need to execute some async ...

Determine the exact location where the mouse was clicked on a webpage containing an iframe

I am trying to retrieve the mouse position on my HTML page, but I am encountering some issues. Here's what I have so far: document.onclick = function(click) { if (click.clientX<340){ myControl.inputs.selection = false; btnRotate.remove ...

Guide to streaming JSON data from a Node.js server to a client JavaScript file using Express and MongoDB

Recently delving into Nodejs and Express, I've encountered an issue when trying to retrieve data from mongoDB and display it on the client browser. While I can successfully pull the values from the mongoDB query, I'm facing a challenge in sending ...

Is it necessary for me to use bindActionCreators?

While going through a post, I couldn't help but notice that the bindActionCreators method from redux wasn't being utilized. Is there a specific reason for this? Could it be that the method is not necessary in this context? The post in question ...

What is the best way to incorporate Vue.js component dependencies into a multi-page application (MPA

When working with a multiple page app, incorporating a component inside another component can be challenging, especially without using a build system. $ npm install sagalbot/vue-select <template> <div id="myApp"> <v-select :value.sy ...

Sending values from loop to a JavaScript function

I have the code snippet below: var storedNames = JSON.parse(localStorage.name); var mytable = "<table> cellpadding=\"0\" cellspacing=\"0\"><tbody><tr>"; for (var i = 0; i < storedNames.length; i++) { if ( ...

Retrieve information and functions from one component in a separate component

I currently have two components: ContainerSidebar.vue <!-- Sidebar --> <div id="b-sidebar"> <div class="change-image"> <img :src="profile.avatar != null ? profile.avatar+'#&apo ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Despite the use of v-if and v-else directives in Vue 2, a specific component properties are not being updated while the others are updating

Vue2 is not updating one specific component (<Button>) inside v-if and v-else, while the rest of the content is updated. I have recently discovered a solution to make this code function, but I am still unsure about Vue2 re-rendering behavior. I worr ...

What steps do I need to take to ensure that the external API proxy for Angular 8 functions properly, without automatically defaulting to

In my current project, I'm attempting to set up a development Angular application to streamline the process of writing and testing services for our main NativeScript app in production. One of the challenges I've encountered is dealing with the C ...

Tips for choosing the desired test to execute with Nightwatch Programmatic API

Currently, I am in the process of developing a web application that enables me to execute Nightwatch tests through a visual interface. At this point, I have successfully been able to run all my tests using a post request from my web app utilizing the Nig ...

Why does JavaScript function flawlessly in FireFox, yet fails completely in other web browsers?

When it comes to browsing, FireFox is my go-to browser, especially for testing out my website Avoru. However, I recently encountered an issue when checking the functionality of my code on other major browsers like Google Chrome, Opera, and Safari. It seems ...

Template literal types in TypeScript and Visual Studio Code: An unbeatable duo

I'm encountering an issue while attempting to utilize literal types in Visual Studio Code. When following the example from the documentation, https://i.stack.imgur.com/V6njl.png eslint is flagging an error in the code (Parsing error: Type expected.e ...

Trouble with the Sendhub API

I'm currently working with the sendhub API and encountering an error. The error message states that the specified format 'application/x-www-form-urlencoded' does not have a deserialization method available. It is recommended to double-check ...

Challenges in designing an Angular application: tackling the spinner and autocomplete functionality

Looking to connect to a REST API that returns a JSON response for implementation of a self-completion feature. The aim is to display a spinner during the autocompletion process until the data retrieval is complete. Although the autocomplete functionality ...