Invoke an RxJs observable to handle errors and retry the process

I have an observable called submit$ that submits a form. If this observable encounters an error with status code 403, it means the user is not authorized and needs to log in first.

Is there a way to automatically trigger another observable when a specific error code occurs? This new observable would handle the authorization process. Once the authorization is successful, I want the submit$ observable to be repeated without requiring the user to manually invoke it again.

Here are the steps I envision:

  1. The user attempts to submit the form and the submit$ observable is activated
  2. An error with status code 403 is encountered
  3. The observable then calls a separate authorise$ observable which handles the authorization workflow
  4. Upon successful authorization, the submit$ observable is triggered again
  5. The process concludes with either success or error
  6. If an error arises during the authorization process, the submit$ operation is terminated

Answer №1

My approach in this code snippet involves separating the process into two observables, submit$ and authenticationSubmit$, which are then merged back together. It should be noted that I have not yet tested this code and there appears to be duplication in the http.post(...) calls, deviating slightly from your described method.

import { merge } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

...

const submit$ = http.post(...);

const authenticationAndSubmit$ = submit$.pipe(
  filter(httpResponse => httpResponse.status === 403),
  switchMap(() => authService.login()),
  filter(authResult => authResult === 'success'),
  switchMap(() => http.post(...))
);

merge(submit$, authenticationAndSubmit$)
  .pipe(
    filter(httpResponse => httpResponse.status === 200),
  )
  .subscribe(httpResponse => {
    // Perform necessary actions here
  });

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

Retrieving various properties of an object by matching IDs and displaying them without repeated reductions

I'm interested in finding a more efficient way to retrieve properties from a reduced object within a Vue component or wrapper DOM element. Let's say I have these two data objects in my component: player: [{ active: true, id: 0, name: &q ...

Using TypeScript to deserialize JSON into a Discriminated Union

Consider the following Typescript code snippet: class Excel { Password: string; Sheet: number; } class Csv { Separator: string; Encoding: string; } type FileType = Excel | Csv let input = '{"Separator": ",", "Encoding": "UTF-8"}&ap ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

"Have you ever wondered how the router object in express.js is seamlessly integrated with app.use(), considering that it only accepts

I am curious about the process of how the router object in express.js is passed to app.use(), which typically only accepts callbacks. Since router is an object of express, I am trying to understand why app.use() does not throw an error even though it req ...

The error message states: "change is not defined"

I am encountering an issue where I have 4 input boxes triggering a function on keyup using the onkeyup event. Strangely, I keep receiving an error stating that "change" (the function's name) is not defined. Despite correctly defining the function, I c ...

Error Encountered During JavaScript Form Validation

Currently, I am troubleshooting a website that was created by another developer. There is a form with JavaScript validation to ensure data is accurately entered into the database. However, I am puzzled as to why I keep receiving these alert messages. Pleas ...

Loading templates (partials) in Angular.js on the fly

Is there a way to dynamically load templates into an Angular app based on a parameter within a ng-foreach loop? <body ng-app="MyApp" ng-controller="ExampleController as example"> <div ng-repeat="item in example.items" class="someClass" ng-swi ...

Improving efficiency for handling a vast number of inputs in React applications

Dealing specifically with Material UI, I am faced with the challenge of rendering a large number of inputs (more than 100) while effectively managing global state. Performance issues arise when using the Material UI <TextField /> component, with noti ...

Webpack bundling, however, encountering issues with resolving TypeScript from the node_modules package

Hey everyone, I've been exploring various approaches to tackle this issue. We are working with two folders within a makeshift mono-repo structure (without using yarn workspace). One folder is named Mgt-Shared and the other is Server. We have set up a ...

Issue with Vue parent component's inability to listen to event emitted by child component

Child component is triggering a custom event: <template> <div id="controls-container" class="controls-container"> <div class="control-button icon-zoom-in" @click="zoomHandler('+')"></div> <div class="control- ...

Can you guide me on how to access an Angular route using a URL that includes query parameters?

Within my current development project, I have implemented a user profile route that dynamically navigates based on the user's _id. This means that when a user accesses the page, their _id is stored in localStorage and then used to query MongoDB for th ...

TypeScript does not pay attention to additional properties in the return type of the setState function

I'm completely lost here. I don't understand why typescript allows me to return anything in the setFormValidation call as long as I include the prevState spread in the return object. It seems to ignore all other properties that I return in the ob ...

Allowing the OPTIONS method in CORS when sending a REST request from AJAX to a WCF Service

After spending 7 hours scratching my head, I am still unable to figure this out. Despite my extensive search on the web, no luck has come my way. My Angular App is sending requests to a WCF command-line hosted service application. To bypass CORS, I utilize ...

Are there any JS/jQuery plugins available for sliding animations that include slideLeft and slideRight functions, similar to the slideUp and slideDown functions?

Does anyone know of a jQuery/JS plugin that combines fading and sliding effects, specifically with slideLeft and slideRight functions similar to jQuery's slideUp and slideDown? I'm hoping to find something ready-made rather than having to build i ...

The image referenced in the assets folder could not be located within the SCSS

Although I've come across similar questions, none of the solutions provided seem to work for me. I've tried them all, but they just don't seem to do the trick. My goal is quite simple - I just want to set a background image using CSS. Howev ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...

PHP query will execute even in the absence of clicking the button

I'm encountering an unusual issue. I've defined a query to insert two names into the database, and I've used Javascript(Jquery) to ensure it only runs when the create button is clicked. However, the script seems to be executing every time I ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Easily move a group of HTML elements at the same time with a simple

Exploring HTML5 Drag and Drop with Multiple Elements When it comes to dragging and dropping multiple elements in HTML5, there seems to be a limitation with the default draggable attribute. This attribute allows only one element to be dragged at a time, ma ...