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

struggling with configuring dependency injection in NestJS and TypeORM

Struggling with integrating nestjs and typeorm for a simple CRUD application, specifically facing issues with dependency injection. Attempting to modularize the database setup code and import it. Encountering this error message: [ExceptionHandler] Nest ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

Utilizing variables to set the templateUrl in Angular2

Trying to assign a variable to the templateUrl in my component, but it's not functioning as expected. @Component({ selector: 'article', templateUrl: '{{article.html}}', styleUrls: ['styles/stylesheets/article.comp ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Condense styles and templates into inline format using Angular-cli

Can anyone help me with configuring angular-cli to support inlining of css and html resources during the build process? I am currently using angular-cli version 1.0.0-beta.24. I attempted building with both ng buld and ng build --env=prod --target=product ...

What role does typescript play in this approach?

test.js const testList = [1, 2, 2, 4, 5, 2, 4, 2, 4, 5, 5, 6, 7, 7, 8, 8, 8, 1, 4, 1, 1]; const lastIndex = testList.findLastIndex((e:number) => e === 100); // Property 'findLastIndex' does not exist on type 'number[]'. Did you mean ...

When using html2canvas in Angular, it is not possible to call an expression that does not have a call signature

I'm currently working on integrating the html2canvas library into an Angular 8 project. Despite trying to install the html2canvas types using npm install --save @types/html2canvas, I'm still facing issues with its functionality. Here's how ...

What are the steps to implement the `serialport` library in `deno`?

After tinkering with Deno to extract readings from an Arduino, I encountered a roadblock when it came to using the serialport library correctly. Here is what I attempted: According to a post, packages from pika.dev should work. However, when trying to use ...

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

What is behind the occurrence of the 'createObjectURL' error?

I am attempting to capture an image using the camera on my laptop. Previously, it was functioning flawlessly, but now I am encountering an error in my console: ERROR Error: Uncaught (in promise): TypeError: Failed to execute 'createObjectURL&apo ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

Managing a MySQL database in NodeJS using Typescript through a DatabaseController

I'm currently working on a restAPI using nodejs, express, and mysql. My starting point is the app.js file. Within the app.js, I set up the UserController: const router: express.Router = express.Router(); new UserController(router); The UserControll ...

The request.files property in express-fileupload is consistently coming back as undefined

I am trying to achieve the task of uploading a file from my browser and sending it via POST to an Express.js application, which will then download the file using express-fileupload. Here is the client-side JavaScript code I have written so far: // Triggere ...

Testing the functionality of an event through unit test cases

I'm currently working on writing unit test cases for the function shown below: selected (event:any) { let selectedValue = event.target.value.substring(0,3); this.seletedBatch = selectedValue; this.enableSubmitButton = true } My test cases are a ...

The error message "Directive does not contain a property called 'element'.ts" is displayed

I'm encountering an issue where the property 'element' is not recognized on 'directive'. I am currently working on implementing functionalities for directives. import { Directive, ElementRef, HostListener } from '@angular/cor ...

CoursesComponent does not contain a Directive annotation

I have been following a tutorial online at this link: https://www.youtube.com/watch?v=_-CD_5YhJTA Unfortunately, I keep encountering the following error message: EXCEPTION: No Directive annotation found on CoursesComponent Here is an excerpt from my a ...

Dragging and dropping in Angular does not move to the intended location within a mat dialog

Attempting to manipulate the order of a lengthy list by dragging and dropping items. In a basic component, moving an item is uncomplicated - able to drag it anywhere within the list. While dragging, can scroll through contents beyond visible range and dro ...

Tips for concealing query parameters that are empty or undefined in Angular 2

I'm currently working with Angular2 (RC2) and the new Router (Alpha.8). Is there a way to prevent a query parameter from being displayed in the URL if it is undefined? For example: this.router.navigate(["/results", this.month, this.day], { ...

Having difficulties in accessing an API with Ionic 3

Whenever I attempt to connect with an API, I keep encountering the Cross-Origin Read Blocking (CORB) blocked cross-origin response error. Can anyone provide guidance on how to resolve this issue? Any assistance would be greatly appreciated. ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...