javascript - 如何使函数执行在角度上同步?
问题描述
场景是:
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!");
}
);
}
}
答案将不胜感激!
解决方案
您需要一个标志,它表明执行是否已经在运行。我假设,如果它已经在运行,你想完全跳过它:
// 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;
});
}
}
推荐阅读
- android - RGBAW 中与 ColorMatrix 相关的“W”值的上下文是什么?
- amazon-web-services - terraform aws - 如何将默认路由添加到 vpc 默认路由表?
- javascript - 悬停时显示随机图像
- python - Python 简单代码我无法修复 help1!1
- typescript - 如何在纯 javascript 中访问 typescript 模块?
- kubernetes - 如何使用 Traefik 和 Kubernetes 启用客户端证书身份验证?
- laravel - 如何在 Laravel::Storage 中使用带有自定义 cname 的“temporaryUrl”和 Amazon S3 -> CloudFront 并使用 Cname
- sql-server - 操作存储过程中的数据列表以在另一个存储过程中使用
- .net - 将 ComboBox SelectedValue 绑定到 Nullable(Of Integer) 属性会引发 InvalidCastException
- python - python install pip 出现错误“ModuleNotFoundError: No module named '_struct'”