简体   繁体   English

了解Angular中的变更检测和异步功能

[英]Understanding change detection and async functions in Angular

I am trying to understand the change detection and template updating in Angular. 我试图了解Angular中的更改检测和模板更新。 I am actually a little confused. 我实际上有点困惑。

I have a button and a simple input field. 我有一个按钮和一个简单的输入字段。 When the button is clicked I change the input field's value to "test". 单击按钮后,我将输入字段的值更改为“ test”。 Then make an async function which returns immediately. 然后创建一个异步函数,该函数立即返回。 Then I wait for around 4 seconds using a for loop (for testing purposes). 然后,我使用for循环等待4秒钟左右(用于测试)。

  • What I expect is: Input field's value becomes "asynched" immediately, since it is an async call. 我期望的是:输入字段的值立即变为“异步”,因为它是异步调用。
  • Reality : Input field's value becomes "asynched" after 4 seconds. 现实:输入字段的值在4秒钟后变为“异步”。

Code

  updateField(){
    this.textContentMain.title = "test"
    this.asyncTestFunction();
    for(var i=0;i<3999999999;i++){

    } 
  }

  asyncTestFunction() {
    this._contentSalesTextConfigService.get(this.contentSalesTextConfig).subscribe(item => {
        this.textContentMain.title = "asynced";
    })
  }

Template 模板

<button (click)="updateField()">Update</button>
<input  [ngModel]="textContentMain.title" #titleAccessor="ngModel" name="title" id="title"  type="text" >

Here is the flow of execution, This should clear all your doubts 这是执行流程,这应该清除所有疑问

// 1. This function will be called as soon as clicked
updateField(){
    this.textContentMain.title = "test" // 2. changes the value
    this.asyncTestFunction(); // 3. call async function
    for(var i=0;i<3999999999;i++){ // 5. start for loop 

    } 
    // 6. end for loop
}

asyncTestFunction() {
    this._contentSalesTextConfigService.get(this.contentSalesTextConfig) // 4. call the http request
    .subscribe(item => {
        this.textContentMain.title = "asynced"; // 7. asap response is received and for loop finish its execution this wiil be executed.
    })
}

Why => 7. asap response is received and for loop finish its execution this wiil be executed. 为什么=> 7.接收到asap响应,并且for循环完成其执行,这将被执行。 (why it waits for "for loop" to finish)? (为什么要等待“ for循环”完成)?

For this you have to read event-loop 为此,您必须阅读事件循环
Watch this the best video which can explain the key thing behind the scene: 观看此最佳视频,可以解释幕后的关键内容:

What the heck is the event loop anyway? 无论如何,事件循环到底是什么?

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

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