从异步函数更新 Angular 视图
Updating Angular view from async function
我有一个初始化一些变量的异步方法。我正在使用的库提供了一个 onProgress
回调来获取当前通过的百分比。我想在我的视图中显示此百分比,但该视图仅在加载过程完成后才会更新。然而,console.log
语句会定期打印。我错过了什么?
import {Component, OnInit} from '@angular/core';
import * as tf from '@tensorflow/tfjs';
@Component({
template: `<button (click)="loadModel()">Load</button>
<p>{{progress}}</p>
`
})
export class LoadModelComponent {
progress: number = 0;
async loadModel() {
this.model = await tf.loadGraphModel('./model.json', {
onProgress: fraction => {
this.progress = fraction;
console.log(this.progress);
}
});
}
一个简单的解决方案可能是
async loadModel() {
this.model = await tf.loadGraphModel('./model.json', {
onProgress: fraction => {
setTimeout(() => {
this.progress = fraction;
console.log(this.progress);
}, 0);
}
});
}
setTimeout
会强制 angular 重新呈现 HMTL
会不会是进度调用 运行 在变化检测区域之外?可能是。但在那种情况下,您可以使用以下
export class LoadModelComponent {
progress: number = 0;
constructor(private ngZone: NgZone) {}
async loadModel() {
this.model = await tf.loadGraphModel('./model.json', {
onProgress: fraction => {
this.ngZone.run(() => {
this.progress = fraction;
});
console.log(this.progress);
}
});
}
我有一个初始化一些变量的异步方法。我正在使用的库提供了一个 onProgress
回调来获取当前通过的百分比。我想在我的视图中显示此百分比,但该视图仅在加载过程完成后才会更新。然而,console.log
语句会定期打印。我错过了什么?
import {Component, OnInit} from '@angular/core';
import * as tf from '@tensorflow/tfjs';
@Component({
template: `<button (click)="loadModel()">Load</button>
<p>{{progress}}</p>
`
})
export class LoadModelComponent {
progress: number = 0;
async loadModel() {
this.model = await tf.loadGraphModel('./model.json', {
onProgress: fraction => {
this.progress = fraction;
console.log(this.progress);
}
});
}
一个简单的解决方案可能是
async loadModel() {
this.model = await tf.loadGraphModel('./model.json', {
onProgress: fraction => {
setTimeout(() => {
this.progress = fraction;
console.log(this.progress);
}, 0);
}
});
}
setTimeout
会强制 angular 重新呈现 HMTL
会不会是进度调用 运行 在变化检测区域之外?可能是。但在那种情况下,您可以使用以下
export class LoadModelComponent {
progress: number = 0;
constructor(private ngZone: NgZone) {}
async loadModel() {
this.model = await tf.loadGraphModel('./model.json', {
onProgress: fraction => {
this.ngZone.run(() => {
this.progress = fraction;
});
console.log(this.progress);
}
});
}