gpt4 book ai didi

angular - 什么时候使用 zone.run()?

转载 作者:太空狗 更新时间:2023-10-29 18:35:16 25 4
gpt4 key购买 nike

我试着阅读了很多关于 NgZone 的文章。我了解到 Angular 使用 zone.js 进行变化检测。我看到一些代码使用了 zone.run 并在其中放置了一些操作。

它实际上做了什么?

我仍然无法弄清楚 zone.run 的实际用途

this.zone.run(() => {
/* my code here */
});

借助这个link ,我有点明白了。

最佳答案

答案本身在您提到的博客中提供。我会尝试进一步分解它。在given example :

Situation: You are creating a progress-bar component whose value will be updated every 10 milli seconds

没有NgZone :

一次button被点击,increaseProgress()将调用一个函数(进度条完成后将显示其值)

    <button (click)="processWithinAngularZone()">
Process within Angular zone
</button>

它每 10 毫秒调用一次,并且不断增加 this.progress柜台100

increaseProgress(doneCallback: () => void) {
this.progress += 1;
console.log(`Current progress: ${this.progress}%`);

if (this.progress < 100) {
window.setTimeout(() => {
this.increaseProgress(doneCallback);
}, 10);
} else {
doneCallback();
}
}

这会起作用,但是 因为我们使用的是 setTimeout , ChangeDetection10 milliseconds 将触发一次循环这将影响应用程序的性能


NgZone :

ngZone我们路过,zone.run()而不是 console.log .这基本上可以作为 ChangeDetection 的触发器。一旦计数器完成。

现在,要避免 setTimeout 的影响(由于猴子修补而触发 ChangeDetection),我们将整个执行 block 包装在 this.zone.runOutsideAngular 中. ChangeDetection仅在我们显式调用 zone.run() 时调用.

  this.zone.runOutsideAngular(() => {
this.increaseProgress(() => {
this.zone.run(() => {
console.log('Outside Done!');
});
});
});

类似的用例:

  1. 假设您需要在 scrollEvent 上实现一些逻辑这可能会触发一个可能导致触发 ChangeDetection 的函数.为了避免这种情况,我们可以使用 zone.runOutsideAngular并手动触发 ChangeDetection使用 zone.run() 执行特定操作/持续时间后.

  2. 您正在使用一些第 3 方库(在 Angular 之外工作 ChangeDetection )并且您需要手动触发 CD在该第 3 方库发生某些事件之后。

它不是很频繁地使用它,但是是的,它会在不为人知的情况下产生不需要的行为。

我希望它能帮助你更好地理解这个概念

关于angular - 什么时候使用 zone.run()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com