首页 文章

了解Angular中的更改检测和异步函数

提问于
浏览
0

我试图了解Angular中的更改检测和模板更新 . 我其实有点困惑 .

我有一个按钮和一个简单的输入字段 . 单击按钮时,我将输入字段的值更改为“test” . 然后创建一个立即返回的异步函数 . 然后我使用for循环等待大约4秒(用于测试目的) .

  • What I expect is: 输入字段的值立即变为"asynched",因为它是异步调用 .

  • Reality : 输入字段的值在4秒后变为"asynched" .

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";
    })
  }

模板

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

1 回答

  • 2

    这是执行的流程,这应该清除你所有的疑虑

    // 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.
        })
    }
    

    为什么=> 7.收到asap响应并且循环完成它的执行,这将被执行 . (为什么它等待“for loop”完成)?为此,你必须阅读事件循环观看这个最好的视频,它可以解释场景背后的关键事项:无论如何,事件循环到底是什么?

相关问题