Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details:

Application Entities :

  • Location - an entity with attributes: FanZone fanZone, and
    List<LocationAdministrator> locationAdmins
  • FanZone - an entity with attribute:
    List<FanZoneAdministrator> fanZoneAdmins

Idea:

  • When a user fills out the form shown below and clicks "NEXT", a Location object is saved in one of my Angular services. This data will not be POSTed until the user completes filling in administrator information (the admin form appears after clicking "NEXT").

https://i.stack.imgur.com/guA4I.jpg

  • After the user fills in the Location Information form from the picture above, they must then fill in the information for Location Administrators and Fan Zone Administrators using the form below.

https://i.stack.imgur.com/EHqpF.jpg

  • Once the user successfully fills in the administrator forms as shown above, I want to register the Location entity (send a POST request). After the Location entity has been posted, I aim to send a series of HTTP POST requests to register a list of LocationAdministrator and FanZoneAdministrator entities sequentially.

Angular code:

next() {

    this.locationService.registerLocation(this.location).subscribe(
      (response: Response) => {
        console.log('Successfully registered Location!');
        console.log(response.json());
      },
      (error: Response) => {
        console.log('Error occurred while trying to register new Location');
      }
    );

    var fanZoneAdmin: User;

    this.registerFanZoneAdminForm.get('fanZoneAdminArray').value.forEach(element => {
      console.log(element);
      fanZoneAdmin = new User(element.username,element.password,element.email,element.firstName,element.lastName,element.city,element.phoneNumber, null,null,null,null, null,this.location.fanZone,null,new Role("FZA"),null);

      this.usersService.registerFanZoneAdmin(fanZoneAdmin).subscribe(
        (response: Response) => {
          console.log('Successfully registered Fan Zone Administrator!');
          console.log(response.json());

        },
        (error: Response) => {
          console.log('Error occurred while trying to register new Fan Zone Administrator');
        }
      );
    });

    console.log('Submitting Location Administrator!')
    var locationAdmin: Location;

    this.registerLocationAdminForm.get('locationAdminArray').value.forEach(element => {
      console.log(element);
      locationAdmin = new User(element.username,element.password,element.email,element.firstName,element.lastName,element.city,element.phoneNumber,  null, null,null, null, null,null,this.location, new Role("LA"),null);

      this.usersService.registerLocationAdmin(locationAdmin).subscribe(
        (response: Response) => {
          console.log('Successfully registered Location Administrator!');
          console.log(response.json());
        },
        (error: Response) => {
          console.log('Error occurred while trying to register new Location Administrator');
        }
      );
    });

    console.log('DONE!')

  }

NOTE:

this.registerFanZoneAdminForm.get('fanZoneAdminArray').value.forEach(element => {..})
is used because of FormArray. The value is an
Array<FanZoneAdministrators>
and each element represents a single FanZoneAdministrator. (This applies to
registerLocationAdminForm.get('locationAdminArray').value.forEach(element=>{..})
as well.)

The sequence of HTTP requests should follow: Location -> List of Fan Zone Administrators -> List of Location Administrators

Any assistance on this matter would be highly appreciated!

Answer №1

Once the current request receives a response, you can proceed with sending the next request.

Take this illustration as an example:

let fanZoneAdminArray = this.registerFanZoneAdminForm.get('fanZoneAdminArray').value;
let locationAdminArray = this.registerLocationAdminForm.get('locationAdminArray').value;

this.locationService.registerLocation(this.location).subscribe((response: Response) => {
    fanZoneAdminRecursion(0, fanZoneAdminArray, () => {
        locationAdminRecursion(0, locationAdminArray, () => {
            // All requests have been sent.
        });
    });
});


let fanZoneAdminRecursion = (index, array, onDone) => {

    let fanZoneAdmin = new User(element.username,element.password,element.email,element.firstName,element.lastName,element.city,element.phoneNumber, null,null,null,null, null,this.location.fanZone,null,new Role("FZA"),null);

    this.usersService.registerFanZoneAdmin(fanZoneAdmin).subscribe((response: Response) => {
      if(index < array.length - 1){
          fanZoneAdminRecursion(++index, array, onDone);
      }else{
         onDone();
      }
   });      
}


let locationAdminRecursion = (index, array, onDone) => {

  let locationAdmin = new User(element.username,element.password,element.email,element.firstName,element.lastName,element.city,element.phoneNumber,  null, null,null, null, null,null,this.location, new Role("LA"),null);

  this.usersService.registerLocationAdmin(locationAdmin).subscribe((response: Response) => {
      if(index < array.length - 1){
          locationAdminRecursion(++index, array, onDone);
      }else{
          onDone();
      }
  });
}

The use of recursion allows for sequentially processing elements in the array after each response is received.

To simplify this process, one could leverage Promises. With promises, handling multiple asynchronous calls becomes as straightforward as

Promise.all(firstCall, secondCall, ....)
.

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

At times, the Ajax response may be lacking in content. However, the response tab in Google

My goal is to retrieve responses from an AJAX call and store them in the global scope for easy access throughout my website. var getOrderStatus = getOrderStatus(), getUserData = getUserData(), orderFormReady = $.when(getOrderStatus, getUserData), ...

Vue.js does not receive the MQTT response message

I am a beginner with Vue and I'm currently working on a project where I need to set a default value for Vue data return(). Right now, when the code runs, it logs console.log('INSIDE CLIENT ON MESSAGE"). However, the value defined as this.roo ...

Enhance the functionality of the kendo grid by incorporating additional buttons or links that appear when the

Is there a method to incorporate links or buttons when hovering over a row in a kendo grid? I've searched through the documentation and looked online, but haven't found a solution. I'm considering if I should modify my row template to displa ...

Obtaining solely the words found within HTML documents

In my Python 2.7 project, I have a folder containing multiple HTML pages that I need to extract only words from. My current process involves opening the HTML file, using the Beautiful Soup library to extract text, and then writing it to a new file. However ...

How can I merge these two Observables in Angular to create an array of objects?

Let's say we are working with two different datasets: student$ = from([ {id: 1, name: "Alex"}, {id: 2, name: "Marry"}, ]) address$ = from([ {id: 1, location: "Chicago", sid: 1}, {id: 2, location: &qu ...

Can you explain the distinction between declaring type using the colon versus the as syntax?

Can you explain the variation between using the : syntax for declaring type let serverMessage: UServerMessage = message; and the as syntax? let serverMessage = message as UServerMessage; It appears that they yield identical outcomes in this particular ...

stop all HTML5 videos when a specific video is played using jQuery

I am facing an issue with 10 HTML5 videos on the same page, CHALLENGE Whenever I click on different videos, they all start playing simultaneously... <div><video class="SetVideo"></video><button class="videoP"></button>< ...

Troubles with displaying Google Maps on Ionic Modal

Having trouble displaying the google map in an ionic modal - it shows up fine on the page but not in the modal. Any help would be greatly appreciated, as this is quite frustrating. Below is my controller js and code for the ionic modal. $ionicModal.from ...

What is the process for eliminating a field from an Angular Reactive Form?

I am working with an Angular form that needs to be sent to the API and it includes 4 fields: username, email, password, and confirmpassword. However, I only want to send three of them - username, email, and password. Does anyone have any suggestions on ho ...

Initiating an Ajax POST request when the onblur() event is triggered

Having an issue with Ajax. I'm trying to submit a changed value from an input field on the onblur() event, but there's a flicker that's bothering me. When I enter a new value and click away, the old value briefly flashes back before changi ...

Calling a Coldfusion function from JavaScript/jQuery using a remote server connection

Although I am well-versed in JavaScript/jQuery, I am a newcomer to ColdFusion. After extensive research, I still can't figure out what seems like it should be a simple problem. My goal is to trigger a server-side call to a ColdFusion function from wi ...

What is the best way to eliminate an item from an array in JavaScript or AngularJS?

I'm attempting to eliminate objects from an array and retrieve the resulting array. I've been using a remove function, but it's not functioning as expected. Here is the input I'm working with: The goal is to remove all values in the ar ...

Tips for ensuring the Google+ JavaScript tag is W3C compliant

I have a Google+ button on my website that is functioning properly. However, when I run it through the W3C validator, an error is detected: The text content of the script element does not meet the required format: It was expecting a space, tab, newlin ...

What is the process for incorporating JavaScript files into an Angular project?

I have a template that works perfectly fine on Visual Studio. However, when I try to use it on my Angular project, I encounter an issue with the JavaScript code. I have filled the app.component.html file with the corresponding HTML code and imported the ...

What is the best way to handle multi-dimensional JSON data without keys in JavaScript?

My JSON data is structured as follows: { "bitcoin": [ "-0.47", "-0.46", "-0.42" ], "maker": [ "8.29", "8.29", "6.89" ] } I want to extract values from this data where keys are not specified. How can I achieve this? Update: Tha ...

Experiencing a strange response while attempting to parse the result of an Angular 2 HTTP JSON request

After successfully implementing the http.get call and retrieving data from the request, I encountered an issue: this.http.get('https://data.cityofnewyork.us/resource/xx67-kt59.json').subscribe(data => { // Read the result field from the ...

Turning spring form data into a JSON object via automation (with a mix of Spring, jQuery, AJAX, and JSON)

Recently, I've set up a spring form that utilizes ajax for submission. Here's an overview of my form... <form:form action="addToCart" method="POST" modelAttribute="cartProduct"> <form:input type="hidden" ...

Setting up RTL (Right to Left) functionality in Material UI version 5 - A Step-by-Step Guide

After updating my app to version 5 of Material-UI from version 4, I noticed that the RTL support is no longer functioning. I carefully followed the instructions in the documentation: https://mui.com/guides/right-to-left/ The current outcome is that the ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

Unleashing the power of jQuery, utilizing .getJSON and escaping

When I use .getJSON, the response I get is a JSON string with many \" characters. However, the callback function does not fire when the page is launched in Chrome. I have read that this happens because the JSON string is not validated as JSON (even th ...