简体   繁体   中英

Updating Angular view from async function

I have a async method that initializes some variable. The library I'm using is offering a onProgress callback that gets the current percentage passed. I want to display this percentage in my view, but the view is only getting updated when the loading process is finished. The console.log statements however are printing regularly. What am I missing?

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

An easy solution could be

async loadModel() {
  this.model = await tf.loadGraphModel('./model.json', {
    onProgress: fraction => {
      setTimeout(() => { 
        this.progress = fraction;
        console.log(this.progress);
      }, 0);
    }
  });
}

setTimeout would force angular to rerender the HMTL

Could it be that the progress call is running outside the change detection zone? Maybe. But in that case, you can make it work with the following

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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