首页 > 解决方案 > 如何使函数执行在角度上同步?

问题描述

场景是:

ServiceA 由两个具有输入的组件访问。ComponentA 有 textArea 并且 ComponentB 有切换按钮。在更改这些组件时,调用 ServiceA.save()。save() 进行 HTTP 调用。

现在的问题是:

我在componentA的textarea中输入文本并直接单击componentB的切换(不点击textArea)。因此 2 个事件 - blur 和 click - 同时发生并调用 ServiceA.save()。这是另一个 API 的主要调用,而前一个调用未完成。我如何检查或停止它,直到另一个呼叫完成?

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

答案将不胜感激!

标签: javascriptangularfunctionasync-await

解决方案


您需要一个标志,它表明执行是否已经在运行。我假设,如果它已经在运行,你想完全跳过它:

// 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;
  });
}
}

推荐阅读