首页 > 解决方案 > 如何等待服务调用完成调用,一旦成功,在 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
                });
            }
        });
    }

标签: angularfile-uploadxmlhttprequest

解决方案


您可以使用 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 
  }) 
);

推荐阅读