[英]How to block UI until all pending operations are complete?
I have an Angular 8 web app with NgxSpinner .我有一个带有NgxSpinner的 Angular 8 网络应用程序。 I'm using it to block UI when some lengthy process is in progress to prevent users from interacting with complex forms while some parts haven't yet fully loaded.
当一些冗长的过程正在进行时,我使用它来阻止 UI,以防止用户在某些部分尚未完全加载时与复杂的表单交互。
The problem is that NgxSpinner hides itself immediately if some process calls hide
, no matter if there is still another process with its own show/hide
call pair running.问题是,如果某个进程调用
hide
,NgxSpinner 会立即隐藏自己,无论是否还有另一个进程运行自己的show/hide
调用对。 So, the web page is unblocked too early when any shorter process has been completed and has called spinner.hide()
.因此,当任何较短的过程完成并调用
spinner.hide()
时,网页会过早解除阻塞。
Here's Stackblitz example.这是Stackblitz 的例子。
How do I make the NgxSpinner to wait for the last hide
to match all show
calls?如何让 NgxSpinner 等待最后一次
hide
匹配所有show
调用?
PS It seems an issue with many UI block libraries I've tried - they just don't account for parallel processes calling show/hide
multiple times. PS 这似乎是我尝试过的许多 UI 块库的一个问题——它们只是没有考虑多次调用
show/hide
并行进程。
Create one service for spinner and keep show/hide count there.为微调器创建一项服务并在那里保持显示/隐藏计数。
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);
}
}
So when showIndex
and hideIndex
equals you need to hide spinner.因此,当
showIndex
和hideIndex
相等时,您需要隐藏微调器。
Call in your component调用你的组件
this.mySpinner.show(); // show spinner
this.mySpinner.hide(); // hide spinner
Here is example in Stackblitz .这是Stackblitz 中的示例。
you can make a use of Promise.你可以使用 Promise。 Each Process function will return a promise and then you can make a use of Promise.all function which will be called once all the promise is resolved.
每个 Process 函数都会返回一个承诺,然后你可以使用 Promise.all 函数,一旦所有的承诺都被解决,它就会被调用。 you can hide the spinner in promise.all method.
您可以在 promise.all 方法中隐藏微调器。 Please find below the sample code.
请在下面找到示例代码。
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.