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

Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone. Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there a ...

Using jest-dom without Jest is definitely an interesting challenge that many developers may

Can anyone help me with extending Typescript interfaces? I have come across a situation that I am trying to solve. In my tests, I am utilizing expect without using Jest directly (I installed it separately and it functions properly). Now, I am interested ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

Hiding a pop-up element and updating the state to False when clicking anywhere outside the element in the background

Presented here is my Search.js component. class Search extends Component { state = { doctors: [], showTab: false } openTab = () => { this.setState({showTab: true}); console.log('openTab state', this ...

How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services. My current approach involves the following code: // ...

What is the best way to implement a modal that can toggle dark mode using the Konami code, with the added functionality of a close button?

Recently, I attempted to create a Modal window that would activate when the Konami code (↑↑↓↓←→←→BA) is typed. As someone new to JavaScript, I'm still learning and open to feedback. While I have the coding part figured out, I need assi ...

Steps to switch the displayed ionicon when the menu is toggled

My goal is to display the 'menu-outline' ionicon on my website until it is clicked, at which point the icon will change to 'close-outline' and vice versa. I am utilizing jQuery for this functionality. Although I am aware of how to togg ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

Encountering error #426 in NextJs when the app is loaded for the first time in a new browser, but only in a

Encountering a strange error exclusively in production, particularly when loading the site for the first time on a new browser or after clearing all caches. The website is built using nextjs 13.2.3 and hosted on Vercel. Refer to the screenshot below: http ...

Utilizing JSON Data for Dynamically Displaying Database Objects on a Google Map

After carefully reviewing the information provided in the initial responses and working on implementation, I am updating this question. I am currently utilizing the Google Maps API to incorporate a map into my Ruby on Rails website. Within my markets mode ...

Can you explain the meaning and significance of the @Injectable annotation?

Is the use of @Injectable indicating that we are able to inject MyService into other classes, or does it mean that we can inject other classes into MyService? @Injectable({ providedIn: 'root' }) export class MyService { constructor() { } } ...

Combine the content from multiple text areas and submit it to another text area

****UPDATE**** Thanks to @JasonB, I was able to resolve the previous issue mentioned. Now, I have three additional textareas on the same form that should only appear when their respective checkboxes are clicked. How can I integrate this into my current sc ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...

drawImage - Maintain scale while resizing

I am currently working on resizing an image using drawImage while maintaining the scale. Here is what I have so far... window.onload = function() { var c = document.getElementById("myCanvas"); var ctx = c.getContext(" ...

Tips for combining a select option and search field into a seamless integrated feature

I'm looking to implement a search field in my project that includes the ability to select specific parameters before running the search. I want it to have a seamless design similar to the image shown below. Although I couldn't find a matching co ...

Is there a way to delete a stylesheet if I only have limited information about the url?

I am attempting to dynamically remove a CSS stylesheet using JavaScript or jQuery. I am aware that the target stylesheet is located within the 'head' element and includes the text 'civicrm.css', however, I do not possess the full URL o ...

What is the best way to reach nested iframes?

I am looking for a solution to send post messages (window.postmessage) to iframes. Currently, it is functioning properly with a single iframe inside the parent page. However, I want it to also work for nested iframes. Here are the criteria: I should on ...

Display a div every 3 seconds with the help of jQuery

I am seeking a solution to display the second div (box2) every 3 seconds. Can anyone help me achieve this using jQuery? <div id="box1" style="background-color:#0000FF"> <h3>This is a heading in a div element</h3> <p>This ...

The event on the full calendar is stuck in place and will not budge

function moveEvent(event, delta, revertFunc) { console.log(event.title + " has been moved to " + event.start.format()); var page = '../include/UpdateCalendarEvent.php'; $("#dialog") .data('start', event.start.format ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...