我正在用 Angular 和 .NET 开发一个系统,我在其中上传文件并想添加进度条。
我已经成功地用对话框显示它:
<p-dialog [(visible)]="dProgressBar" [style]="{width: '50vw', 'text-align': 'end'}" [modal]="true"
header="Loading...">
<ng-template pTemplate="content">
<div>
<p-progressBar *ngIf="progressBarVisible" [value]="value"></p-progressBar>
</div>
</ng-template>
</p-dialog>
在我的组件中,我声明:
value = 0;
progressBarVisible = false;
在同一个组件中,我有一个函数可以向我的服务发出如下请求:
getArchivo(formData: FormData) {
this.blockedPanel = true;
this.dProgressBar = true;
this.progressBarVisible = true;
this._http.post('/Files', formData).then((res: any) => {
if (res && !res.error) {
this.blockedPanel = false;
this.progressBarVisible = false;
this.dProgressBar = false;
// Rest of the code...
}
});
}
我的服务:
public async post(method: string, payload: any = {}): Promise<any> {
this.http.post(`${this.apiUrl}${method}`, payload, {
reportProgress: true,
observe: 'events',
})
.subscribe(
(event) => {
if (event.type === HttpEventType.UploadProgress && event.total !== undefined) {
// This is an upload progress event. Compute and show the % done:
const progress = Math.round(100 * event.loaded / event.total);
this.progresoSubject.next(progress);
} else if (event instanceof HttpResponse) {
console.log('File is completely uploaded!');
console.log(event.body);
}
},
(error) => {
this.progresoSubject.next(-1); // Notify the component of an error
this.message.add({
severity: 'error',
summary: 'Error querying',
detail: error.message,
life: 5000,
});
}
);
}
到目前为止,该栏已正确显示,但在进入方法之前它已被填充。我已经通过添加断点来更好地可视化进度来确认这一点,但它不起作用。
如果有人可以提供一个示例,正如我所研究的那样,没有发现需要在服务器端添加任何内容。
您好,非常感谢。
您的服务方法是异步的,并且您的组件中不等待
post
方法。
async getArchivo(formData: FormData) {
this.blockedPanel = true;
this.dProgressBar = true;
this.progressBarVisible = true;
try {
const res: any = await this._http.post('/Files', formData).toPromise();
if (res && !res.error) {
}
} catch (error) {
} finally {
this.blockedPanel = false;
this.progressBarVisible = false;
this.dProgressBar = false;
}
}