Making retries with the RetryWhen filter in Angular 2 RxJS Observables when encountering errors in the status

I'm currently working with the Angular 2 HTTP library, which returns an observable. I'm trying to set up a retry mechanism for specific error statuses/codes.

The problem I'm facing is that when the error status is not 429, Observable.of(error) gets executed in the error case for retries. However, if all two retries fail, the flow continues to the success block instead of the catch block.

Is there a way to ensure that the flow goes to the catch block when all retry attempts fail?

    return this.http.get(url,options)
           .retryWhen((errors) => {
                      return errors
                            .mergeMap((error) => (error.status === 429) ? Observable.throw(error) : Observable.of(error))
                            .take(2);
                     })
                       .toPromise()
                       .then((res:Response) => console.log('In Success Block'))
                       .catch((res) => this.handleError(res));

Do you think this solution will address my issue?

        return this.http
  .post(url, JSON.stringify(body), requestOptions).retryWhen((errors) => {
    return errors
      .mergeMap((error) => (error.status === 404) ? Observable.throw(error) : Observable.of(error))
      .take(2);
  }).map((res:Response) =>{
    if (res.status === 200)
      return res;
    else
      return Observable.throw(res);
  })
  .toPromise();

Answer №1

Although I'm a bit late to the event, I recently integrated a similar feature. Check out my approach:

  submitRequest<T>(endpoint: string, payload: any): Observable<T> {
    return Observable.defer(() => {
        return super.submitRequest<T>(endpoint, payload);
    }).retryWhen((error) => {
        return this.refreshToken(error);
    });
}

The function for refreshing tokens:

refreshToken(observable: Observable<any>): Observable<any> {
    return observable
        .switchMap((response: any) => {
            if (response.status === 401) {
                return Observable.of(response);
            }
            return Observable.throw(response);
        })
        .scan((acc, value) => {
            return acc + 1;
        }, 0)
        .takeWhile(acc => acc < 3)
        .flatMap(() => {
            console.log('Refreshing token and retrying');
            return this.authService.issueRefreshToken();
        });
}

This functionality triggers a token refresh and retries the initial request with the updated token whenever a 401 status code is received during an HTTP request. The switchMap handles returning a new Observable in case of a 401 error, preventing further retry attempts.

Here's how you would incorporate this logic into your code (where the error block is executed upon receiving Observable.throw(x)):

 this.apiService.submitRequest(data).subscribe(response => {
      ...
        }
    }, error => {
        ...
        }
    });

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

Sortable layouts and tables in Ionic 3

I found a great example of an Ionic table that I'm using as reference: https://codepen.io/anon/pen/pjzKMZ <ion-content> <div class="row header"> <div class="col">Utility Company Name</div> <div c ...

Is there a way to specify the sequence in which Observables are subscribed to in Angular?

Working with API calls in a service.ts file has brought me some challenges. Here is the code snippet: //code getCars() { this.car = this.http.get(car_url) return this.car; } getTires() { this.tires = this.http.get(tires_url) return this.tires; } getSeat ...

Monitor a universal function category

Trying to implement a TypeScript function that takes a single-argument function and returns a modified version of it with the argument wrapped in an object. However, struggling to keep track of the original function's generics: // ts v4.5.5 t ...

The Angular component template fails to reflect the current value received from the observable

I am facing an issue with a component that updates its state from a service observable: import {Component} from '@angular/core'; import {SessionTimeoutService} from "./session-timeout/session-timeout.service"; import {Observable} from & ...

A versatile method to organize a multi-dimensional array of items

I need help sorting a nested array using a generic function. The sorting should be based on the values of the items within the nested array. Here is an example of my array: type Person = { id: number, name: string, childs: Child[] } type Chil ...

Typescript: Convert Generics to a String Format

Is there a way for me to return a generic type as a string in this function? const actionName = <P extends string>(path: P) => <A extends string>(action: A): string => `${path}/${action}`; const path = actionName('filter'); con ...

When the form field is double-clicked, it automatically populates with information, but unfortunately it does not meet the

Presented below is a formgroup configuration: this.order = new FormGroup({ City: new FormControl('', Validators.required), Street: new FormControl('', Validators.required), DateOfDelivery: new FormControl('', Vali ...

Best practices for Rest API design: Enumerate potential values for entity attributes

Exploring the most effective method for populating dropdown lists in a UI with data and determining the optimal REST URI structure to support this process. Let's consider an entity called Car, which includes an attribute called "type". The type attr ...

Angular routing is giving me trouble when trying to open various menus at the same location

I am new to Angular and facing a situation where my HomeComponent has a reference to the Appmenucomponent in its .html page. I need to be able to click on different menus (each leading to a new component) and have them open in the same place (div), similar ...

Angular allows for the dynamic updating of og meta tags

Sharing dynamic content on WhatsApp has been made possible through an API. By utilizing the angular Meta class in my component.ts file, I am able to dynamically update the default meta tag property in index.html with the latest content. ...

Issue encountered in app.module.ts while attempting to incorporate AngularMultiSelectModule

Currently, I am utilizing angular version 6 and attempting to incorporate the angular2-multiselect-dropdown in my application. Upon launching the app and following the steps outlined in this guide: and also here: https://www.npmjs.com/package/angular2-mul ...

When attempting to add mp3 files to a Vue/TypeScript application, a "Module not found" error is triggered

I am encountering an error while trying to import .mp3 files into my Vue/Typescript app. Upon running 'npm serve', I am presented with the following message: ERROR in /Users/***/***/application/src/components/Sampler.vue(80,16): 80:16 Cannot fin ...

Angular - passing information to a nested component

Within my application, I have a main component along with three sub-components. I am passing data to these three sub-components and using setTimeout to manage the timing of the data being sent. The first sub-component displays for 5000 milliseconds. The ...

Angular is incorrectly updating all fields at once instead of updating only the intended one field

I am facing an issue with my *ngFor loop where I am attempting to update a number field on click, but it ends up updating all the items with the same value. Here is a snippet of my HTML: <form *ngFor="let product of products" [formGroup]=&quo ...

Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList. https://i.stack.imgur.com/rFlM2.png I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an ...

Having trouble resolving the typescript package while integrating with another module

Attempting to develop a basic npm package with TypeScript and bundle it using webpack. When trying to use the package in another module, such as a react application named 'module A.' Within module A, the 'myLibrary' package is installe ...

Tips for obtaining the rotation angle within the Ionic gesture API?

Currently, I am working on canvas and facing an issue while handling gesture events with Hammer.js. Despite seeking help in various forums, including this one, I have yet to receive a response. Now, I am trying my luck with Ionic gestures but struggling to ...

Transform a string into title case and eliminate any special characters in Angular 6

I've written some code that displays text in title case using a pipe. {{person.name| titlecase}} Now, I want to create another filter or pipe that will remove special characters from the string and only keep numbers and letters. For example: "john ...

Angular 13 encounters issues loading Bootstrap and JS files whenever the route button is clicked

As a beginner in Angular, I am currently working on converting HTML templates to Angular for the purpose of learning. However, I have encountered an issue when navigating to the signup page from the home's router link. The bootstrap and JS files are n ...

What is the reason behind the file not found error encountered when running Deno with the command "echo hello"?

Exploring Deno's standard library, I encountered an issue with Deno.run - a function designed to create a new subprocess. Here is the example provided in the documentation: const p = Deno.run({ cmd: ["echo", "hello"], }); When I attempt to run ...