问题可能是由于使用了mat-progress-bar组件中的动态值绑定而导致。在文件上传过程中,进度百分比可能不会立即显示。以下是一种解决方法,可以通过使用Angular中的ChangeDetectorRef手动检测变化来刷新视图。
在组件代码中导入ChangeDetectorRef模块:
import { ChangeDetectorRef } from '@angular/core';
在组件类中的构造函数中添加ChangeDetectorRef服务:
constructor(private changeDetectorRef: ChangeDetectorRef) {}
重载ngOnInit方法并在其中添加以下代码:
ngOnInit() { this.uploadForm = this.formBuilder.group({ file: [''] }); this.watchFileUploadProgress(); }
添加一个名为watchFileUploadProgress()的函数,用来监控文件上传的进度,并在视图中刷新进度百分比的显示:
watchFileUploadProgress() { if (this.uploadedFiles && this.uploadedFiles.length > 0) { const fileUploadObservable = from(this.uploadedFiles); fileUploadObservable.pipe(mergeMap((uploadResult: any) => { const statusObservable = this.apiService.trackUploadStatus(uploadResult.data.id); return statusObservable; } )) .subscribe( (result: any) => { this.uploadProgress = 0; this.progress = 0; result.bytesTransferred = isNaN(result.bytesTransferred) ? 0 : result.bytesTransferred; result.totalBytes = isNaN(result.totalBytes) ? 0 : result.totalBytes; this.progress = roundToTwo((result.bytesTransferred / result.totalBytes) * 100); this.uploadProgress = this.progress.toFixed(0); this.changeDetectorRef.detectChanges(); }, (error: any) => { this.sharedService.openSnackBar(UPLOAD_ERROR_MESSAGE); }, () => { } ); } }
其中,apiService.trackUploadStatus()是一个用来查询文件上传状态的服务。绑定的进度值为this.progress,在函数中通过ChangeDetectorRef手动进行了视图刷新,在uploadProgress变量中存储