【问题标题】:Understanding change detection and async functions in Angular了解 Angular 中的变更检测和异步函数
【发布时间】:2017-10-26 12:19:22
【问题描述】:

我正在尝试了解 Angular 中的更改检测和模板更新。我其实有点迷茫。

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

  • 我的期望是:输入字段的值立即变为“异步”,因为它是一个异步调用。
  • 现实:输入字段的值在 4 秒后变为“异步”。

代码

  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" >

【问题讨论】:

  • 我在这里可能是错的,但您的摘要周期可能在函数执行之前不会执行。你的同步函数与你的 for 循环是分开的,为什么你的 for 循环在那里我不确定。不过我的想法是 for 循环就是你在等待的。
  • 只有在当前上下文中的所有内容都完成后,异步调用才会始终解决。 get 被添加到“待办事项列表”中,然后函数的其余部分在该列表被检查下一步之前运行。这与 Angular 的更改检测无关,它在实际设置标题值时按预期运行。
  • 非常感谢@jonrsharpe

标签: angular asynchronous data-binding angular2-changedetection


【解决方案1】:

这是执行的流程,这应该可以解决您所有的疑问

// 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 收到响应,for 循环完成执行 这将被执行。 (为什么要等待“for循环”完成)?

为此,您必须阅读事件循环
看这个最好的视频 可以解释幕后的关键:

What the heck is the event loop anyway?

【讨论】:

  • 非常感谢,for 循环用于测试。这样我就可以检测到什么时候会发生什么。您的回复非常明确,谢谢。据我了解, asyncTestFunction 在被调用时执行并立即获得响应,但是当 updateField() 函数结束其执行时执行回调..@Vivek
  • 不会调用api,一般api调用需要时间,此时angular会继续工作,直到得到api响应,一旦收到响应,就会执行subscribe里面的代码(第 7 名)
  • 让我们说 for 循环设置为运行 30 秒。服务器在 2 秒后响应。如我所见,订单仍然相同@Vivek
  • 所以它会等待 30 秒来更新 / 因为事件循环,如果没有 for 循环将在 2 秒内更新它,请观看我发布链接的视频,它会炸毁你的介意。
  • 如果能解决您的疑虑,请接受答案。 @rematnarab
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 2017-05-25
相关资源
最近更新 更多