[英]How to make function execution synchronous in angular?
場景是:
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;
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.