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!

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software