what is the use of Zone.js in Angular 2
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.
Solution 1:
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
- http://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html
- http://blog.kwintenp.com/how-the-hell-do-zones-really-work/
Solution 2:
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.
Solution 3:
Zone.js is the key to Angular's change detection.
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. This lets Angular know that it can run its change detection algorithms and re-render anything that has changed.
This minimizes any rendering churn and makes it efficient.
Solution 4:
In simple language Zone.js is a api or set of programs which is used by angular 2 to update the application view when any change occurred.
A Zone is an execution context that persists across asynchronous task. for example:Events, XMLHttpRequests and Timers(setTimeout(), setInterval()) etc.
Solution 5:
Zone.js uses for async calls and internally for the error and stack trace angular 2 is using it. So you cannot ignore this script.