简体   繁体   中英

How to make function execution synchronous in angular?

The scenario is:

ServiceA is accessed by two components having inputs. ComponentA has textArea and ComponentB has toggle button. On change of these components, ServiceA.save() is called. save() does HTTP call.

Now the problem is:

I enter text in textarea of componentA and directly click on toggle of componentB (Without clicking out of the textArea). Hence 2 events - blur and click - occurred at the same time and ServiceA.save() is called. This is the leading calling of another API while the previous call isn't complete. How do I put a check or stop it until the other call completes?

export class ServiceA {
  constructor() {}
  save() {
    this.ServiceB.callApi(reqLink, key, data).subscribe(
      (resData) => {
        console.log("API successful!");
      },
      (rej) => {
        console.log("Error occured!");
      }
    );
  }
}

The answers would be appreciated!

You need a flag, which signals if the execution is already running. I assume, you want to completely skip the execution if it's already running:

// Use a class variable as a flag
private saveIsRunning = false;
save(){    
  // Skip the execution, if it's already running.
  if (this.saveIsRunning) {
    return;
  }
  this.saveIsRunning = true;

  this.ServiceB.callApi(reqLink, key, data).subscribe((resData) => {
    console.log('API successful!');
    this.saveIsRunning = false;
  },
  (rej) => {
    console.log('Error occured!');
    this.saveIsRunning = false;
  });
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM