了解 Angular 中的变化检测和异步函数
Understanding change detection and async functions in Angular
我正在尝试了解 Angular 中的变更检测和模板更新。其实我有点懵。
我有一个按钮和一个简单的输入框。
单击该按钮后,我将输入字段的值更改为 "test"。然后立即创建一个 returns 的异步函数。然后我使用 for 循环等待大约 4 秒(出于测试目的)。
- 我期望的是: 输入字段的值立即变为 "asynched",因为它是一个异步调用。
- 现实: 输入字段的值在 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. 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. (why it waits for "for loop" to finish)?
For this you have to read event-loop
Watch this the best video which
can explain the key thing behind the scene:
我正在尝试了解 Angular 中的变更检测和模板更新。其实我有点懵。
我有一个按钮和一个简单的输入框。 单击该按钮后,我将输入字段的值更改为 "test"。然后立即创建一个 returns 的异步函数。然后我使用 for 循环等待大约 4 秒(出于测试目的)。
- 我期望的是: 输入字段的值立即变为 "asynched",因为它是一个异步调用。
- 现实: 输入字段的值在 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. 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. (why it waits for "for loop" to finish)?
For this you have to read event-loop
Watch this the best video which can explain the key thing behind the scene: