与绑定进度功能一起使用时,Angular Bootstrap Progressbar无法更新

时间:2019-01-23 17:25:40

标签: javascript angular ng-bootstrap

我正在将文件上传到IPFS节点,该节点使用进度功能来处理更新。如您所见,我将 this 绑定到处理函数,以便它可以访问所有必需的变量

//This method controls uploading the waveform to IPFS
uploadWaveform()
{
    this.ipfs.files.add(buf, {progress:this.handler.bind(this)})
      .then((result) => {
          console.log("All done!");
          this.progressText = "All Done!";

    });
}

进度处理函数是一个简单的函数,它仅更新uploadProgress变量,如下所示:

handler (p) {    
  this.uploadProgress = Math.round(100*p/this.fileSize);      
}

我正在使用类似ng-bootstrap的进度条:

<ngb-progressbar [value]="uploadProgress">
  <i>{{progressText}}</i>
</ngb-progressbar>

当我上传文件时,它可以正确上传并且进度功能可以正常工作。

但是,ng-bootstrap进度栏中的uploadProgess变量未更新。如果我单击该应用程序内的任何位置,它将更新该值,但在此之前不会更新。

我知道它实际上是在组件内部进行更新的,因为如果在上载完成后5秒钟后超时以打印出progressText的值,则它会反映出更新后的值!

      setTimeout(() => {
        console.log("this.progressText = " + this.progressText);
      }, 5000);

任何人都知道为什么该组件未更新?我认为这是一些奇怪的绑定问题...预先感谢。

3 个答案:

答案 0 :(得分:3)

也许进度回调函数handler被不正确地调用,您可以在uploadProgress回调中更新NgZone

首先在组件的构造函数中注入NgZone实例

constructor (private zone: NgZone) { }

然后在uploadProgesss函数中对您的handler进行修改

handler (p) {
  this.zone.run(() => {
    this.uploadProgress = Math.round(100.0 * p / this.fileSize);
  });
}

答案 1 :(得分:0)

使用Bootstrap进度在ts中创建一个函数来计算完成百分比。

  <div ngClass="progress">
    <div ngClass="progress-bar progress-bar-success" 
         role="progressbar" aria-valuemin="0" aria-valuemax="100" [style.width]="getPercentage()+'%'" >
      <div class="pl-2">{{getPercentage()}} %</div>
    </div>
  </div>

组件中的功能应为完成百分比的值。每当代码中有任何更新时,angular都会重新加载该函数以获取更新的值。

complete=0
 getPercentage() {
return Math.round(100*this.complete/this.fileSize);    
}

答案 2 :(得分:0)

尝试使用NgZone'https://dzone.com/articles/understanding-ngzone'

handler (p) {
  this.zone.run(() => {
    this.uploadProgress = Math.round(100.0 * p / this.fileSize);
  });
}