简体   繁体   English

Angular中的代码如何执行?

[英]How can I follow the code execution in Angular?

I feel like I have zero understanding of how code is executed in Angular.我觉得我对 Angular 中的代码是如何执行的理解为零。 I have this basic example, where I create an empty array.我有这个基本示例,我在其中创建了一个空数组。 In a constructor, I print the array and then I call a method, inside of which I print the array again, then I have a loop and I put 5 objects in that array and I print it again.在构造函数中,我打印数组,然后调用一个方法,在其中我再次打印数组,然后我有一个循环,我将 5 个对象放入该数组并再次打印它。 How come that all the printouts are arrays with data?为什么所有的打印输出都是带有数据的 arrays? Could someone explain me the how is this happening?有人可以解释一下这是怎么回事吗? Also some link to relevant documentation or deeper explanation would be great, I couldnt find much in Angular docs.还有一些相关文档的链接或更深入的解释会很棒,我在 Angular 文档中找不到太多。

console安慰

stackblitz (look at the console) stackblitz (看控制台)

properties: Property[] = [];
constructor() {
    console.log("Before", this.properties);
    this.getProperties();
}

getProperties() {
    console.log("Before1", this.properties);
     for (var i = 0; i < 5; i++) {
         this.properties[i] = new Property({
             key: "test" + i,
             label: i + "d",
             value: i + "d",
             required: true,
             order: i + 1
         });
     }
    console.log("After1", this.properties.sort((a, b) => a.order - b.order));
}

To follow code execution, you either add a要跟踪代码执行,您可以添加一个

debugger;

command in your code (that's like a hard-coded breakpoint)代码中的命令(就像硬编码的断点)

Or you can open your dev tools and the desired file (eg on your question):或者您可以打开您的开发工具和所需的文件(例如关于您的问题):

在此处输入图像描述

and click on line numbers to add breakpoints manually:并单击行号以手动添加断点:

在此处输入图像描述

In JS files, you can select some code and use the contextual menu:在 JS 文件中,您可以 select 一些代码并使用上下文菜单:

在此处输入图像描述

You can either evaluate its value at a given time, or put in into the watches (on the right):您可以在给定时间评估其价值,也可以将其放入手表中(右侧):

在此处输入图像描述

Which will then track its value throughout your code.然后它将在整个代码中跟踪其值。

While debugging you will see the correct value调试时您将看到正确的值

When you open the object to check the value the chrome console takes the lastest value and shows it.当您打开 object 检查值时,chrome 控制台会采用最新值并显示它。 So that's why your all comsole.log holds the same value这就是为什么您的所有 comsole.log 都具有相同的值

Try this尝试这个

console.log(JSON.stringify(this.properties));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM