Chaining asynchronous HTTP requests in Angular 2: A guide to stopping execution if one request fails

I am faced with a challenge of executing an array of HTTP requests in a specific order, where if any request fails, the subsequent ones should not be executed.

  1. Is there a way to achieve this requirement?

  2. What would be the recommended approach to handle this scenario?

In order to address this issue, I have developed the following solution:

  let failed: boolean = false;
  payloadArray.forEach(payload => {
     if (!failed) {
     http.post(this.url, payload, this.options)
     .map((res: Response) => {
        return res.json;
      })
    .catch((error: any) => {
          failed = true;
          Observable.throw(error.json().error || 'Server error')
       });
     }
  }

Answer №1

To achieve this functionality, a custom Observable creator is needed that merges emitted values and subscribes in sequence after each completion. As far as I know, such functionality is not available in the RxJs library.

I have developed a factory method that should provide the desired outcome:

public sequence(requests: Array<Observable<Response>>): Observable<Response[]> {
    return Observable.create((observer) => {
        const output = [];

        function executeHttp() {
            const request = requests.pop();
            if (request) {
                request.take(1).subscribe((value) => {
                    output.push(value);
                    executeHttp();
                }, (ex) => {
                    observer.error(ex);
                });
            } else {
                observer.next(output);
                observer.complete();
            }
        }

        executeHttp();
    });
}

It's important to note that I included a take(1) operator for the HTTP observables. This ensures that the HTTP observables are destroyed after emitting a response, eliminating the need to manually call unsubscribe. You can also use first() as an alternative, which serves the same purpose but behaves differently when no value is emitted.

If you come across any operators that meet your requirements, please inform me.

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

Utilizing JavaScript variables imported from an external library in Next.js: A Guide

I am currently working on a Next.js with Typescript website and I am in the process of adding advertisements. The ad provider has given me instructions to embed this JavaScript code on my site: <script src="//m.servedby-buysellads.com/monetization. ...

The type definition file for 'bson' could not be located. It appears to be missing from the program due to being the entry point for the implicit type library 'bson'

I recently set up a new Typescript/React project and encountered the following error in the tsconfig.json file: "Cannot find type definition file for 'bson'. The file is in the program because: Entry point for implicit type library 'bson&ap ...

I'm experiencing difficulty in scrolling on my Nextjs web application

Currently, I am facing an issue with my portfolio webpage which is divided into 3 main components - Hero, About, and Portfolio. The layout structure is as follows: export default function RootLayout({ children, }: { children: React.ReactNode }) { ret ...

What is the best way to integrate retrieved data into Next.js with TypeScript?

Hello everyone! I recently started working with Next.js and TypeScript. Currently, I'm attempting to use the map() function on data fetched from JsonPlaceholder API. Here is my implementation for getStaticProps: export const getStaticProps: GetStatic ...

How to make a routerLink clickable within an anchor tag in Angular 6

I am facing a peculiar issue with a group of hyperlinks. html <div class="col-12 navlinks"> <div class="text-center"> <div class="justify-content-center"> <a class="col-auto d-inline-block whitelink" rou ...

What is the best way to use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

ERROR: There was a problem with the NgbTabset class at line 12 in the inline template. This issue occurred because the 'templateRef' property could not be read as it was undefined

I am utilizing ng-bootstrap instead of ui-bootstrap in angular2 for my project. This is the HTML code I am using: <div class="row" style="height: 100%;"> <div class="col-12"> <div class="container" id="contentMain"> <div ...

Updating the node startup file with Visual Studio 2015 using NodeJS/Typescript

Encountering a persistent error: Error Code: TS5055 Cannot write file C:/project/dir/server.js' because it would overwrite the input file. Project: TypeScript/JavaScript Virtual Projects Even after renaming my entry filename to nodeserver.js, the ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

Is it possible to invoke a Python function with arguments from an HTML document (when using Django)?

Currently, I am in the midst of developing a Django application, and I seem to have encountered a minor hurdle. Essentially, the backend is successfully returning an HTML page, which is functioning as expected. However, I am facing difficulty in sending d ...

Retrieving JSON data using HTTP GET in Flutter

I am struggling with fetching data. As a newcomer to Flutter, I have been trying to resolve this issue despite reading through various articles. While I was able to retrieve the data individually, I faced difficulty in iterating over it using a loop. Below ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Leverage the extended properties of Express.js's Request's generic arguments

I am currently working on extending the Request type to include a property that relies on the request body. However, I am facing an issue where the generic in catchAsync is not being correctly applied and always defaults to any instead of the specified gen ...

Automatically send authentication information in PHP using HTTP

Is there a way to send the HTTP auth login/password from a PHP file for automatic login without requiring user input? The two websites are not on the same server. Edit: I've been attempting to use cURL, but have been unable to make it work. ...

A guide to properly executing initialization functions in Angular with Electron

Currently, I am working with Angular and Electron. I have a Preferences object that I need to initialize (Preferences.init()) before any other code is executed. Is there a specific location in Angular or Electron where this initialization code should be pl ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

The Angular 5 route guard on a component-less route does not successfully redirect

My current challenge involves setting up a component-less route with a route guard in Angular 5. Here is my code snippet: const routes: Routes = [ {path: '', runGuardsAndResolvers: 'always', canActivateChild:[AppRouteGuard], children: ...

Oops! It seems like there has been an issue. The EnjoyHint is not

Encountered the following error message: https://i.stack.imgur.com/JL4l6.png The error in my code is within the line that initializes a new EnjoyHint object. Seeking assistance to resolve this issue. public initiate(stepName) { const steps = ...

Tips for maintaining the selection when switching pages with smart-table?

I have implemented smart-table in my project to allow users to select records from different pages and view them in a preview section. However, I am facing an issue where the selection made on the first page does not persist when navigating back to it aft ...