Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete successfully, and then proceed with the regular form submission logic.

Below is a simplified version of what I have attempted so far:

async onSubmit(form) {
    if(specialField) {
        const response = await this.updateSpecialField();
    }
    // The rest of the form submission process is abstracted here
}

async updateSpecialField() {
    this.specialService.updateField().subscribe(then => {
        this.specialService.loadingFields$.subscribe(data => {
            this.loading = data;
        });
    });
}

In this scenario, the service call is being made but it always completes after the form submission has already gone through. As this approach didn't yield the desired results, I experimented with using await and promises to ensure that the service call finishes before proceeding.

Here is an alternate version of the updateSpecialField function:

async updateSpecialField() {
    let updatedFieldResponse = await this.specialService.updateField().toPromise();
    return Promise.resolve(updatedFieldResponse);
}

In this case, the execution never reaches the return line and the form submission does not happen. Although the service returns a successful response, the code doesn't continue from where it should.

Answer №1

Give this a shot

async handleSubmit(formData) {
    if(customField) {
        const result = await this.updateCustomField();
    }
    // The details of form submission will remain hidden
  }
  
  async updateCustomField() {
    return this.customService.modifyField().pipe(
              switchMap((_: any) =>
                this.customService.loadFields$.toPromise().then(info => {
                    this.loadingStatus = info;
                })
              )
            ).toPromise();
  }

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

Is there a method we can use to replace fixture fields with data created during the test case to produce a dynamic payload? (Already attempted existing solution)

I am new to using Cypress and I'm wondering if there is a way to generate a dynamic payload by replacing values in a JSON file with values generated programmatically in a Cypress test. This is similar to what we do in Rest Assured by substituting %s i ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

Next.js 13: Dealing with the "Objects are not valid as a React child" error while using async/await to retrieve data

Currently, I am working on a project using Next.js 13 and the new app directory structure. One of my tasks involves fetching data from an API. However, every time I attempt to do this with async/await, I encounter an error message stating: "Objects are not ...

The response body in Superagent is unknown until the next line is executed

While working on testing my express API using Jest and Supertest, I encountered an issue that I cannot seem to resolve: const id = await request.post('/program') .send(body) .expect('Content-Type', /json/) .expect(201).body ...

Arranging the data in my JSON reply

{ "JsonResult": { "List": [{ "Subject": "Something", "Type": 0, "TypeDescription": "Referral" }], } } When I hit my service, I receive a sample JSON response. After that, there is a button with ...

Guide to displaying a loading image when selecting an item from a dropdown menu using JavaScript

When using three drop-down lists and performing an AJAX call on each dropdown list's onclick function, I encountered a delay in loading the data. To address this issue, I attempted to display a loading image while processing the AJAX call. <form ...

The marker is not updating in real-time with the actual latitude and longitude on the Google Maps angular

I have been attempting to update the marker in my Angular Google Map in real-time, but unfortunately it is not working as expected. It only displays the initial static data and then fails to update. Despite conducting a thorough search on Google, I have be ...

Filter the array while maintaining its current structure

I'm struggling to create an array filter that can handle exact and partial data within a nested array structure. The challenge is maintaining the integrity of the top-level structure while filtering based on data in the second layer. Here's an ex ...

Is there a way to bypass the initial result when using document.querySelectorAll?

this is my own unique html content <div class="content-body"> <table style="text-align:center;" class="table table-bordered"> <tbody> <tr> <th>Text Line</th> </tr> <tr> <td> ...

Fastest method to invoke a potentially undefined function

With a background in C#, I am familiar with the null-conditional operator which allows you to call a function while avoiding a potential null-reference exception like this: Func<int> someFunc = null; int? someInteger = someFunc?.Invoke(); // someInte ...

Is there a way to execute a JavaScript function by clicking on an anchor tag?

Many websites, such as StackOverflow, have attempted to address this particular issue. However, the explanations provided are complex and difficult for me to grasp. I am looking for someone who can help identify my mistakes and explain the solution in simp ...

Tips for improving the scrolling function in Java with Selenium for optimal performance

I'm currently working on a project using Java in MAVEN. My task involves retrieving a URL, scrolling down the page, and extracting all the links to other items on that website. So far, I have been able to achieve this dynamically using Selenium, but ...

Issues with Cordova and JQuery ajax functionality not operating as expected

I am facing an issue with implementing AJAX functionality in my Cordova app (CLI 6.3.1) on Visual Studio 2017. It works fine on the emulator, but I encounter a connection error when installing it on a mobile phone. I have already included CSP as shown bel ...

Utilizing Angular 2+ with the [innerHTML] property to incorporate HTML with added style attributes

I am currently utilizing Angular 2+ [innerHTML] input for inserting HTML formatting that includes style tags. Within my template, the code looks like this: <span [innerHTML]="someVar"></span> In the component file, I have defined: someVar = ...

How can I use variables to show the second dropdown list only when a value has been selected in the first dropdown?

Is there any way I can choose a specific value from a dropdown list and based on that selection, show another dropdown list? I understand how to do it with regular words, but what if I use variable names? University Name: <select name="university" id=" ...

Encountering a timeout error while using selenium-webdriver and phantomJS

Currently, I am developing my automated test scripts using a combination of selenium-webdriver, phantomJS, and mocha. The script I am working on is written in JavaScript. One requirement is to wait until a specific element becomes completely visible befo ...

Function anomalies triggered by delayed setState updates with React Hooks

Creating a Quiz app with React involves fetching questions as an array and managing the following states: An array containing all question details - statement, options, chosen answer, status (answered, marked for review, unvisited); An object holding info ...

How can you determine the HTML element where a mouse click took place?

Is it possible in JavaScript to identify the HTML element where a mouse click occurs without having an event listener attached to the elements? Essentially, I want to be able to capture the mouse click event and determine the specific element on the page ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

WebGL annotations failing to display on the webpage

I'm currently working on displaying a 3D model using Three.js in a web browser and looking to incorporate annotations like the ones shown in this Sketchfab model: Interactive 3D Test. I came across a helpful guide at this link, but I'm facing iss ...