簡體   English   中英

如何在所有掛起操作完成之前阻止 UI?

[英]How to block UI until all pending operations are complete?

我有一個帶有NgxSpinner的 Angular 8 網絡應用程序。 當一些冗長的過程正在進行時,我使用它來阻止 UI,以防止用戶在某些部分尚未完全加載時與復雜的表單交互。

問題是,如果某個進程調用hide ,NgxSpinner 會立即隱藏自己,無論是否還有另一個進程運行自己的show/hide調用對。 因此,當任何較短的過程完成並調用spinner.hide()時,網頁會過早解除阻塞。

這是Stackblitz 的例子。

如何讓 NgxSpinner 等待最后一次hide匹配所有show調用?

PS 這似乎是我嘗試過的許多 UI 塊庫的一個問題——它們只是沒有考慮多次調用show/hide並行進程。

為微調器創建一項服務並在那里保持顯示/隱藏計數。

export class MySpinnerService {
  showIndex = 0;
  hideIndex = 0;

  constructor(private spinner: NgxSpinnerService) {}

  show() {
    this.showIndex++;
    this.spinner.show();
    console.log('show spinner', this.showIndex);
  }

  hide() {
    this.hideIndex++;
    if (this.showIndex === this.hideIndex) {
      this.spinner.hide();
      console.log('hide spinner', this.hideIndex);      
    }
  }

因此,當showIndexhideIndex相等時,您需要隱藏微調器。

調用你的組件

this.mySpinner.show(); // show spinner
this.mySpinner.hide(); // hide spinner

這是Stackblitz 中的示例。

你可以使用 Promise。 每個 Process 函數都會返回一個承諾,然后你可以使用 Promise.all 函數,一旦所有的承諾都被解決,它就會被調用。 您可以在 promise.all 方法中隱藏微調器。 請在下面找到示例代碼。

this.spinner.show();
let p1 = new Promise((resolve, reject) => {

  setTimeout(() => {
    resolve();
  }, 3000);

});

let p2 = new Promise((resolve, reject) => {

  setTimeout(() => {
    resolve();
  }, 3000);

});

Promise.all([p1,p2]).then( ()=> {
  this.spinner.hide();
})

您可能想要使用 forkJoin 運算符,在這種情況下,您將在所有請求完成后進入此狀態,然后您將隱藏加載微調器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM