如何找到哪个异步操作触发ngZone(导致更改检测)? [英] How to find which async action triggers ngZone (that lead to Change Detection)?

查看:296
本文介绍了如何找到哪个异步操作触发ngZone(导致更改检测)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Any changes in the stack trace of updates always lead back to globalZoneAwareCallback. How do you find out what triggered the change?

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

In terms of debugging it's good to have a clear picture.

推荐答案

globalZoneAwareCallback是在zonejs中声明的函数,用于使用capture=false处理所有事件回调. (顺便说一句,对于capture=true,有globalZoneAwareCaptureCallback)

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

这意味着任何事件侦听器都将首先使用此方法.该侦听器可以由Angular,您或任何第3方库添加到页面上.

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.

我们可以通过多种方式来监听Angular中的浏览器事件:

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

  • 预订浏览器事件<element (event)="callback()">

@HostListener装饰器@HostListener('event') callback() {}

Renderer2.listen方法

rxjs fromEvent

分配元素属性element.on<event> = callback

addEventListener方法element.addEventListener(event, callback)(此方法在上面以许多其他方式在内部使用)

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

一旦进入globalZoneAwareCallback,您就可以访问所有应触发的区域任务.

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

让我们想象一下,我们在document.body上监听了click事件:

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

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

让我们打开Chrome开发者工具以清楚了解图片:

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

我们刚刚发现的东西:

  • 每个区域任务都包含,因此这是触发更改的原因

  • 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

让我们考虑另一个示例,并使用Angular方式添加click事件:

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

<h2 class="title" (click)="test()">Hello {{name}}</h2>

一旦我们点击该h2元素,我们应注意以下几点:

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

您可能会感到惊讶,现在 callback 属性没有立即将我们带到test回调,而是显示了@angular/platform-browser package的一些包装.其他情况也可能有所不同,但是在这些情况下通常只需要 ZoneTask.source 属性,因为它显示表明您更改的根本原因

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.

这篇关于如何找到哪个异步操作触发ngZone(导致更改检测)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆