简体   繁体   English

如何在 angular 中使 function 执行同步?

[英]How to make function execution synchronous in angular?

The scenario is:场景是:

ServiceA is accessed by two components having inputs. ServiceA 由两个具有输入的组件访问。 ComponentA has textArea and ComponentB has toggle button. ComponentA 有 textArea 并且 ComponentB 有切换按钮。 On change of these components, ServiceA.save() is called.在更改这些组件时,调用 ServiceA.save()。 save() does HTTP call. save() 执行 HTTP 调用。

Now the problem is:现在的问题是:

I enter text in textarea of componentA and directly click on toggle of componentB (Without clicking out of the textArea).我在componentA的textarea中输入文本并直接单击componentB的切换(不点击textArea)。 Hence 2 events - blur and click - occurred at the same time and ServiceA.save() is called.因此 2 个事件 - blur 和 click - 同时发生并调用 ServiceA.save()。 This is the leading calling of another API while the previous call isn't complete.这是另一个 API 的主要调用,而前一个调用尚未完成。 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;
  });
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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