Home >Web Front-end >JS Tutorial >An in-depth analysis of zone.js in Angular and how it works
This article will take you to understand zone.js in Angular, use an example to demonstrate the capabilities of zone.js, and briefly analyze the working principle behind it. I hope it will be helpful to everyone!
Perhaps you have heard that Angular uses zone.js
, but why does Angular use zone.js
? It can What functions are provided? Today we will write a separate article to talk about zone.js
, and its role in the Angular framework will be described in the next article. [Related tutorial recommendations: "angularTutorial"]
What is Zone? The official document explains it this way: Zone is an execution context that spans multiple asynchronous tasks. In a nutshell, Zone has a particularly powerful ability to intercept or track asynchronous tasks. Below we will use an example to demonstrate its capabilities and briefly analyze the working principle behind it.
<button id="b1">Bind Error</button> <button id="b2">Cause Error</button> <script> function main() { b1.addEventListener('click', bindSecondButton); } function bindSecondButton() { b2.addEventListener('click', throwError); } function throwError() { throw new Error('aw shucks'); } main(); </script>
This is a simple HTML page. When the page loads, a click event will be added to the first button. The function of its click event function is to add a click event to the second button, and the function of the click event function of the second button is to throw an exception. We click the first button and the second button in turn, and the console displays as follows:
(索引):26 Uncaught Error: aw shucks at HTMLButtonElement.throwError ((索引):26:13)
But if we start running the code through zone.js
, what will be the difference in the console output? , we first adjust the startup code:
Zone.current.fork( { name: 'error', onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) { console.log(error.stack); } } ).fork(Zone.longStackTraceZoneSpec).run(main);
At this time, the console output is as follows:
Error: aw shucks at HTMLButtonElement.throwError ((索引):26:13) at ZoneDelegate.invokeTask (zone.js:406:31) at Zone.runTask (zone.js:178:47) at ZoneTask.invokeTask [as invoke] (zone.js:487:34) at invokeTask (zone.js:1600:14) at HTMLButtonElement.globalZoneAwareCallback (zone.js:1626:17) at ____________________Elapsed_571_ms__At__Mon_Jan_31_2022_20_09_09_GMT_0800_________ (localhost) at Object.onScheduleTask (long-stack-trace-zone.js:105:22) at ZoneDelegate.scheduleTask (zone.js:386:51) at Zone.scheduleTask (zone.js:221:43) at Zone.scheduleEventTask (zone.js:247:25) at HTMLButtonElement.addEventListener (zone.js:1907:35) at HTMLButtonElement.bindSecondButton ((索引):23:10) at ZoneDelegate.invokeTask (zone.js:406:31) at Zone.runTask (zone.js:178:47) at ____________________Elapsed_2508_ms__At__Mon_Jan_31_2022_20_09_06_GMT_0800_________ (localhost) at Object.onScheduleTask (long-stack-trace-zone.js:105:22) at ZoneDelegate.scheduleTask (zone.js:386:51) at Zone.scheduleTask (zone.js:221:43) at Zone.scheduleEventTask (zone.js:247:25) at HTMLButtonElement.addEventListener (zone.js:1907:35) at main ((索引):20:10) at ZoneDelegate.invoke (zone.js:372:26) at Zone.run (zone.js:134:43)
By comparison, we know: when zone.js
is not introduced, we call it by error The stack only knows that the exception was thrown by the click function of button 2. After introducing zone.js
, we not only know that the exception is thrown by the click function of button 2, but also know that its click function is bound by the click function of button 1, and even know that the initial The application startup is triggered by the main
function. This ability to continuously track multiple asynchronous tasks is extremely important in large and complex projects. Now let's see how zone.js
does it.
zone.js
takes over the asynchronous API provided by the browser, such as click events, timers, etc. It is precisely because of this that it can have stronger control and intervention capabilities for asynchronous operations and provide more capabilities. Now let's take the click event as an example and see how it is done.
proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener,..)
In the above code, proto
refers to EventTarget.prototype
, which means that this line of code redefines the addEventListener
function. Let's continue to see what the makeAddListener
function does.
function makeAddListener() { ...... // 关键代码1 nativeListener.apply(this, arguments); ...... // 关键代码2 const task = zone.scheduleEventTask(source, ...) ...... }
This function mainly does two things. One is to execute the addEventListener
function provided by the browser itself in the custom function. The other is to arrange an event for each click function. Task, this is also an important factor in zone.js
's strong ability to intervene in asynchronous APIs.
Now let’s go back to the example at the beginning of this article and see why the console can output a complete and complete function call stack. We have just analyzed the makeAddListener
function, which mentioned that it arranges an event task for each click function, which is the execution of the zone.scheduleEventTask
function. This schedule event task function actually executes onScheduleTask
:
onScheduleTask: function (..., task) { const currentTask = Zone.currentTask; let trace = currentTask && currentTask.data && currentTask.data[creationTrace] || []; trace = [new LongStackTrace()].concat(trace); task.data[creationTrace] = trace; }
The complete function call stack output by the console at the beginning of the article is stored in currentTask.data[creationTrace]
Inside, it is an array composed of LongStackTrace
instances. Every time an asynchronous task occurs, the onScheduleTask
function records the current function call stack storage. Let’s look at the constructor of the class LongStackTrace
:
class LongStackTrace { constructor() { this.error = getStacktrace(); this.timestamp = new Date(); } } function getStacktraceWithUncaughtError() { return new Error(ERROR_TAG); }
this.error
stores the function call stack. The getStacktrace
function usually calls the getStacktraceWithUncaughtError
function. We see new Error
You can probably know how the entire call stack is obtained.
This article analyzes just an example of the capabilities of zone.js
. If you want to know more functions, you can refer to the official documentation. Through this example, I hope readers can have a general understanding of zone.js
, because it is also an indispensable cornerstone of Angular change detection. I will explain this aspect in the next article.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of An in-depth analysis of zone.js in Angular and how it works. For more information, please follow other related articles on the PHP Chinese website!