【发布时间】:2019-03-08 06:19:09
【问题描述】:
您好,我有一个带有文件上传组件的 Angular 项目。每当用户拖动/选择一个文件时,服务调用就会触发上传该文件。如果有任何错误,那么我会显示一个带有该错误的弹出窗口。我面临的问题是,如果用户选择或拖动 5 个文件,我有 5 个不同的弹出窗口。那么我如何调用第一个服务然后等待完成并上传下一个文件?或者有什么更好的建议吗?
- 在选择或拖动服务调用时
getFile(file) { file.map(obj => { if (!_.find(this.fileList, { fileName: obj.name })) { this.fileList.push(obj); obj.extension = obj.name.substring(obj.name.lastIndexOf('.') + 1); if (_.includes(this.allowedExtensions, obj.extension)) { this.UploadFile(this.fileList).subscribe((data: any) => { if (data) { if (data.response) { this.fileShowList.push(data.response); } } }, (error) => { this.mdDialog.open(ErrorDialogComponent, { 'data': { 'type': 'error', 'title': `error `, 'content': `Error` }, 'disableClose': true }); }); } else { let infoDialog = this.mdDialog.open(ErrorDialogComponent, { 'data': { 'type': 'error', 'title': `File type not allowed`, 'content': `File type not allowed` }, 'disableClose': true }); } } else { let infoDialog = this.mdDialog.open(ErrorDialogComponent, { 'data': { 'type': 'error', 'title': `You cant upload files with same name`, 'content': `You cant upload files with same name` }, 'disableClose': true }); } }); }
-
上传服务调用:
UploadFile(files: Array<any>) { let _self = this; const dataUrl =/Backend/uploadFile; let fileObjectArray: Array<any> = []; return Observable.fromPromise(new Promise((resolve, reject) => { let formData: any = new FormData(), xhr = new XMLHttpRequest(); formData.append('applicationId', 's'); formData.append('token', 'ss'); formData.append('filename', files[0], files[0].name); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { _self.btnText = 'Upload files'; _self.uploadFile = false; let responseObj = JSON.parse(xhr.response); if (responseObj.status.code) { let dialogRef = _self.mdDialog.open(ErrorDialogComponent, { 'data': { 'type': 'error', 'title': responseObj.status.message, } }); dialogRef.afterClosed().subscribe((close: boolean) => { if (close) { _self.ngOnInit(); } }); } else { resolve(JSON.parse(xhr.response)); } resolve(JSON.parse(xhr.response)); } else { reject(xhr.response); } } }; xhr.open('POST', dataUrl, true); xhr.send(formData); })); }
【问题讨论】:
-
可以使用 rxjs 操作符 finalize()。示例 =
this.paymentMessage$ = this.creditCardService.payStorage(equipPayment).pipe( finalize(() => { //Call your service again }) ); -
你必须从 import { finalize } from 'rxjs/operators' 导入它;
-
嗨@PatricioVargas,可以将其显示为答案
标签: angular file-upload xmlhttprequest