当前位置:  开发笔记 > 编程语言 > 正文

如何找到哪个异步操作触发ngZone(导致更改检测)?

如何解决《如何找到哪个异步操作触发ngZone(导致更改检测)?》经验,为你挑选了1个好方法。

更新的堆栈跟踪中的任何更改始终会导致返回globalZoneAwareCallback。您如何找出引发变化的原因?

在调试方面,最好有一个清晰的画面。



1> yurzui..:

globalZoneAwareCallback is a function declared in zonejs for handling all event callbacks with capture=false. (btw, for capture=true there is globalZoneAwareCaptureCallback)

It means that any event listener will first go through this method. That listener can be added on the page by Angular, by you or by any 3rd party library.

There are many ways of how we can listen to browser events in Angular:

subscribe to browser event

@HostListener decorator @HostListener('event') callback() {}

Renderer2.listen method

rxjs fromEvent

assign element property element.on = callback

addEventListener method element.addEventListener(event, callback)(this method is used internally in many other ways above)

Once you're within globalZoneAwareCallback you have access to all Zone tasks that should be triggered.

Let's imagine we listen to click event on document.body:

document.body.addEventListener('click', () => {
   // some code
});

Let's open Chrome dev tools to have a clear picture:

What we've just discovered:

each Zone task contain source so this is what triggers the change

target property shows which object triggers the change

callback property can lead us to the handler of the change

Let's consider another example and add click event using Angular way:

Hello {{name}}

Once we click on that h2 element we should observe the following:

You might be surprised that now callback property didn't bring us to the test callback right away but rather we showed some wrapper from @angular/platform-browser package. And other cases also may differ but ZoneTask.source property is usually all you need in those cases because it shows you the root cause of the change.

推荐阅读
小色米虫_524
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有