angular - 如何等待服务调用完成调用,一旦成功,在 Angular 2 中再次调用相同的服务
问题描述
您好我有一个带有文件上传组件的角度项目。每当用户拖动/选择一个文件时,服务调用就会触发上传该文件。如果有任何错误,那么我会显示一个带有该错误的弹出窗口。我面临的问题是,如果用户选择或拖动 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 =
/后端/上传文件; 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()。 https://www.learnrxjs.io/operators/utility/finalize.html
当 observable 完成或出错时调用方法。
例子:
import { finalize } from 'rxjs/operators';
.
.
.
this.paymentMessage$ = this.creditCardService.payStorage(equipPayment)
.pipe(
finalize(() => {
//Call your service again
})
);
推荐阅读
- python - 我应该在 pandas 中使用什么扩展来检测 .Rout 文件?
- python - 为什么从 np.float16 转换为 np.float32 会修改值?
- javascript - 获取创建元素的 _id 而不是 mongodb 中的整个数据
- spring-boot - 如何下载文件然后在spring控制器中更改视图
- julia - 尝试使用 GeometricFlux.jl 训练变量 GNN
- python - Combine seaborn legends with histplot
- swift - 变异函数可以在延迟后执行进一步的变异吗?
- pine-script - 策略测试:金字塔功能/追踪止损不起作用?
- javascript - 如何在网页中垂直滚动后让元素跟随光标
- python - 配置文件命令(需要一些帮助)