Angular 2中Zone.js的用途是什么?

前端之家收集整理的这篇文章主要介绍了Angular 2中Zone.js的用途是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前正在学习Angular 2.0,我来到了Zone.js文件,我想知道Zone.js文件的目的是什么,以及它如何使我的应用程序更好。
区域是跨异步任务持久存在的执行上下文,并允许区域的创建者观察和控制区域内代码的执行。

我认为在angular2中使用zonejs的主要目的是知道何时渲染。

根据NgZone Primer(第5章:用例/用例3:框架自动渲染)

Frameworks,such as Angular,need to know when all of the application
work has completed and perform DOM update before the host environment
performs the pixel rendering. In practice this means that the
framework is interested when the main task and the associated micro
tasks have executed but before the VM hands over the control to the
host.

@H_502_17@

Angular使用区域来修补异步API(addEventListener,setTimeout(),…),并使用来自这些修补API的通知在每次发生某些异步事件时运行更改检测。

对于这个Angular区域有onMicrotaskEmpty事件

https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/zone/ng_zone.ts#L199

和ApplicationRef订阅此事件以触发更改检测(Application.tick)

https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/application_ref.ts#L405-L406

zonejs也可用于调试,测试和分析。如果您遇到一些错误,它可以帮助您查看整个调用堆栈。

区域补丁异步API如:

Promise
XHR
fetch
Error
addEventListener
removeEventListener
FileReader
WebSocket
MutationObserver
WebKitMutationObserver
document.registerElement
navigator.geolocation.getCurrentPosition
navigator.geolocation.watchPosition

copy cut paste abort blur focus canplay canplaythrough change click contextmenu 
dblclick drag dragend dragenter dragleave dragover dragstart drop 
durationchange emptied ended input invalid keydown keypress keyup 
load loadeddata loadedMetadata loadstart message 
mousedown mouseenter mouseleave mousemove mouSEOut mouSEOver mouseup 
pause play playing progress ratechange reset scroll 
seeked seeking select show stalled submit suspend 
timeupdate volumechange waiting 
mozfullscreenchange mozfullscreenerror mozpointerlockchange 
mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror

setTimeout/clearTimeout
setInterval/clearInterval
setImmediate/clearImmediate

requestAnimationFrame/cancelAnimationFrame
mozRequestAnimationFrame/mozCancelAnimationFrame
webkitRequestAnimationFrame/webkitCancelAnimationFrame

alert
prompt
confirm

这篇文章可能有助于理解它在angular2中的工作原理

> http://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html
> http://blog.kwintenp.com/how-the-hell-do-zones-really-work/

原文链接:https://www.f2er.com/angularjs/144011.html

猜你在找的Angularjs相关文章