Postponing a function invocation in an Angular/TypeScript application

I am facing a challenge in my Angular project. I have a form on one of my pages that allows users to submit data which is then sent to the database. However, after submitting the data, I need to delete the user's information from one table and insert it into another table. The issue arises because both actions occur simultaneously due to being triggered by the same button click event. How can I ensure that the delete function waits until the insert function is completed before executing?

Below is the button responsible for submission and deletion:

<button ion-button full block color="danger"(click)="postDados(form.controls.itemRows);postNeurosensi(formsensi.controls.itemRows3);postEletroneuro(form2.controls.itemRows2);deletaDados()">Enviar</button>

The following are the functions defined in Page.TS file:

 postEletroneuro(req){
    this.service.postEletroneuro(req.value)
    .subscribe(
      data => console.log(data.message),
      err => console.log(err)
   );  
}

deletaDados(){ 
    this.service.deleteData(this.parametroid).subscribe(
      data => {
        console.log(data.message);
        this.getDados();
      },
      err => console.log(err)
    );
}

Now, let's take a look at the service.ts file containing the functions:

postEletroneuro(params){
    let headers = new Headers();
    headers.append('Content-type','application/json');
    return this.http.post(`${this.api}eletroneuro/`, params,{
      headers: headers
  }).map(
    (res:Response) => {return res.json();}
  );
}

deleteData(id){
    console.log(`${this.api}${id}`)
    let headers = new Headers();
    headers.append('Content-type', 'application/json');
    return this.http.post(`${this.api}fichasdia/${id}/`, id,{
      headers: headers
  }).map(
    (res: Response) => {return res.json();}
  );
}

Any suggestions on how to handle this situation?

Answer №1

submitElectroneuroData(req){
    this.electroneuroService.submitData(req.value)
    .subscribe(
      data => {
         console.log(data.message);
         deleteData();
      },
      err => console.log(err)

   );  
  }
  
  deleteData(){ 

    this.electroneuroService.deleteData(this.parametroid).subscribe(
      data => {
        console.log(data.message);
        fetchData();
      }

      ,
      err => console.log(err)
    );      

  }

Call the following function (excluding deleteData):

<button ion-button full block color="danger"(click)="postData(form.controls.itemRows);postNeurosensi(formsensi.controls.itemRows3);submitElectroneuro(form2.controls.itemRows2);">Submit</button>

Answer №2

Here is another way to approach it :

<button ion-button full block color="danger" (click)="postElectroneuro(form2.controls.itemRows2)">Send</button>

component.ts

postElectroneuro(req) {
    this.service.postElectroneuro(req.value)
        .flatMap((data) => {
            console.log("data", data);
            return this.service.deleteData(this.parameterId);
        })
        .subscribe((deleteResponse) => {
             console.log("deleteResponse", deleteResponse);
        })
}

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

What is the best way to refresh information following its removal?

In my app, I have implemented a feature where posts are displayed as HTML cards using a component called PostList. Each card has a delete button to remove it from the list. The issue I am facing is that when I delete a card, it remains visible in the post ...

The tooltip in nvd3 is displaying the index instead of the label

I'm encountering an NVD3 tooltip issue with my multichart (multiline chart). The XAxis labels are set as JAN, FEB, MAR... DEC. However, when I hover over the graph, it displays 0, 1, 2, 3... 11 as the tooltip title instead of the month names. Here is ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

text: Methods for refreshing a Cognito access token in a JavaScript application without generating a client secret in Angull

How can I refresh a Cognito access token in a JavaScript application (AngularJS) if the client application does not generate a client secret? I attempted to use the code snippet below but it resulted in the following error message: {"error":"invalid_clien ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

NodeJS JSONStream causing memory exhaustion issue

I've encountered an issue while trying to stream a large JSON file (94mb in size) from an HTTP request to a local file using the JSONStream library in NodeJS. Despite setting a memory flag of 256mb with node --max-old-space-size=256 .\main.js, th ...

Unable to transfer file using ajax (displaying print_r($_FILES); Array ( ) )

I have encountered an issue with sending a file using XHR compared to a common form confirmation. Here is the HTML code: <form action="ajax/upload.php" method="post" name="form1" enctype="multipart/form-data" id="id1"> <input type="file" name=" ...

I am not enhancing the array's value; rather, I am substituting it

Hey everyone, I'm currently working on extracting an array of Sizes and Colors from an object. The goal is to trigger a handler, clickHandler(), when the input is clicked. However, each time the handler is invoked, the code ends up replacing the value ...

Tips for transferring a variable from Next.js to a plain JavaScript file

When it comes to Canvas Dom operations in my NextJs file, I decided to include a Vanilla JS file using 'next/script'. The code for this is: <Script id="canvasJS" src="/lib/canvas.js" ></Script>. Everything seems to ...

Conditionally Add Columns to jQuery Datatables

I am working with a jQuery datatable to showcase data retrieved through an AJAX request. However, I am interested in adding a third column to the table specifically for administrators, allowing them to delete entries. Can someone guide me on how to incorpo ...

Issue with Checkbox Functionality Between Parent and Child Components in React.js

In the main component, I have four checkboxes. My goal is to display a value from a function in the child component based on whether each checkbox is checked or not. export default class App extends Component { constructor(props) { super(props); ...

Steps to specify a prefix for declaring a string data type:

Can we define a string type that must start with a specific prefix? For instance, like this: type Path = 'site/' + string; let path1: Path = 'site/index'; // Valid let path2: Path = 'app/index'; // Invalid ...

"Exploring the world of arrays and looping in

Can someone assist me with this issue? I am currently stuck in JS Arrays & Loops and I can't understand why it's not returning "0" when the function is empty. function sumArray (numbers) { // your code var numbers = [1, 2, 3, 4]; if (nu ...

Tips for preventing redundant HTTPInterceptor requests when transitioning between RxJS mergeMap operations

My system utilizes two JWT tokens: a Refresh Token (expires after 7 days) and an Access Token (expires after 15 minutes). These tokens are securely stored on httpOnly cookies and can be accessed via the server. The refresh method generates a new token and ...

Struggling to determine the presence of JSON installation

I have encountered an issue with a php file where I suspect that this specific line of code is not functioning properly: sendResponse(200, json_encode($result)); The problem seems to be that the values from my select statement earlier in the program are ...

The ng-model in Angular is unable to capture the initial input value on load

I am currently using a window onload script to obtain longitude and latitude data and pass them to hidden input values. $(function() { window.onload = getLocation; var geo = navigator.geolocation; function getLocation() { if (geo) { geo ...

Just sign up for events one time

A short script was created to use ajax to load pages. Only links with the class ajax-pls should be selected. Once an eventlistener is added, the class is removed so that the included HTML can be parsed each time.... right? (function() { function addEv ...

Troubleshooting: Error message when using getElementById in JavaScript

Issue: While creating a simple demo site to experiment with JavaScript, I encountered a "TypeError: document.getElementById(...) is null" when attempting to change the display value of an element to block upon button click. Despite trying common solution ...

socket.io / settings when establishing a connection

I'm facing an issue in my node.js / Express.js app where I need to pass parameters with the socket.io connection (saw a solution in another post). On the client side, here is a snippet of my code: edit var socket = io.connect('/image/change&ap ...

Unlocking the power of React using TypeScript for optimal event typing

I need assistance with properly typing events in TypeScript. Consider the following function: import * as React from 'react'; someHandler = (event: React.SyntheticEvent<HTMLInputElement> | React.KeyboardEvent<HTMLInputElement>) =&g ...