Currently am learning Angular 2.0 and i come accross the file Zone.js, and i would like to know what is the purpose of the file Zone.js and how will it make my application better.
js is a way of creating a new Context and getting the code executed within that context/Zone. Any code enclosed within a Zone whether synchronous or asynchronous is executed within the same context. Zone. js is basically used to create new context and execute code within it.
Zone creates a wrapper around all asynchronous operations in the browser such as user interactions, HTTP, timers and any other changes that can cause changes in state. Zone knows when any these operations completes. Angular in-turn, subscribes to notifications from Zone for whenever one of these operations completes.
A zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs. This guide describes how to use Angular's NgZone to automatically detect changes in the component to update HTML.
A zone is an execution context that persists across async tasks, and allows the creator of the zone to observe and control execution of the code within the zone.
I think that the main purpose of using zonejs in angular2 is to know when to render.
According to NgZone Primer (Chapter 5: Use Cases/Use Case 3: Framework Auto Render)
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.
Angular uses the zone to patch async APIs(addEventListener, setTimeout(), ...) and uses notifications from these patched APIs to run change detection every time some async event happened.
For this Angular zone has onMicrotaskEmpty
event
https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/zone/ng_zone.ts#L199
and ApplicationRef
subscribes to this event to trigger change detection (Application.tick
)
https://github.com/angular/angular/blob/2.2.4/modules/%40angular/core/src/application_ref.ts#L405-L406
Also zonejs is useful for debugging, testing, profiling. It helps you see whole call stack if you face with some error.
Zone patches async APIs like:
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
This articles might be usefull to understand how it works in angular2
Zonejs is one of the core library used in Angularjs 2. Zonejs is to maintain contextual execution for single or multi-leveled asynchronous methods. So, it means it helps to keep track of the parent context of currently executing asynchronous method.
Example -
Zone.current.fork({}).run(function(){ Zone.current.myZoneVar = true; console.log('Assigned myZoneVar'); setTimeout(()=>{ console.log('In timeout', Zone.current.myZoneVar); },1000); }); console.log('Out side', Zone.current.myZoneVar);
<script src="https://unpkg.com/[email protected]?main=browser"></script>
Note : Plz, ignore the console error. This code working fine in jsfiddle - https://jsfiddle.net/subhadipghosh/0uqc9rdr/
Here we created a fork of our current Zone and run is invoking the method under the Zone. The method has an asynchronous call (setTimeout). But as it is under zone we have the access of Zone variable. In last line we can see out of zone we are trying to access same variable, but it will have undefined in it.
Original post - http://technobelities.blogspot.in/2017/03/zonejs-overview-with-example.html
Angular 2 is utilizing Zonejs for change detection. Whenever any change happens, it is detected by following code in Angular 2 -
ObservableWrapper.subscribe(this.zone.onTurnDone, () => { this.zone.run(() => { this.tick(); }); }); tick() { // perform change detection this.changeDetectorRefs.forEach((detector) => { detector.detectChanges(); }); }
Angular zone emits onTurnDone event to start change detection in the app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With