Home Web Front-end JS Tutorial An in-depth analysis of zone.js in Angular and how it works

An in-depth analysis of zone.js in Angular and how it works

Feb 07, 2022 am 10:09 AM
angular

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!

An in-depth analysis of zone.js in Angular and how it works

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(&#39;click&#39;, bindSecondButton);
  }
  function bindSecondButton() {
    b2.addEventListener(&#39;click&#39;, throwError);
  }
  function throwError() {
    throw new Error(&#39;aw shucks&#39;);
  }
  main();
</script>
Copy after login

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)
Copy after login

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: &#39;error&#39;,
        onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
          console.log(error.stack);
        }
      }
    ).fork(Zone.longStackTraceZoneSpec).run(main);
Copy after login

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)
Copy after login

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,..)
Copy after login

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, ...)
  ......
}
Copy after login

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;
}
Copy after login

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);
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles