【问题标题】:rxjs to launch upload one by one in Angular apprxjs 在 Angular 应用中启动上传一一
【发布时间】:2018-03-08 07:59:01
【问题描述】:

我已经创建了拖放组件来上传文件,用户可以同时上传 5 个文件,但即使我在预览中显示所有图像,我也想在收到服务器对前一个文件的响应后开始上传

使用 rxjs 和 angular(v4) 更好的方法是什么

这是我的代码:

public onFileSelected(event) {
    if (event && event.type == 'uploadImageProject') {

        const previews$ = Observable.from(event.files)
            .filter(file => file instanceof File)
            .map(file => file)
            .take(5)

        const previewSub = previews$.subscribe(file => {
            this.previews = [];
            this.addPreview(file as File);
        });

        this._storeSubscription.push(previewSub);

    }
}

private addPreview(file: File): void {
    const reader = new FileReader();
    reader.onload = (event) => {
        this.uploadFile(event.currentTarget['result']);
        this.previews.push(event.currentTarget['result']);
    };
    reader.readAsDataURL(file);
}

private uploadFile(imgBase64): void {
    const uploadId = UUID.UUID();        
    const fileToUpload = {projectId: this.projectId, upload: {file: imgBase64, id: uploadId, type:'picture', order: 0}};
    this._store.dispatch(addPictureOnProject(fileToUpload));
}

目前脚本可以工作,但上传一起开始,函数 addPreview 在我的应用上显示图片,uploadFile 调度一个动作(redux)来调用服务

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    一些随机的想法:

    你可以得到真正的 rxjs-y 并使用 concatAll,你的 observables 就是你的 http 请求。根据文档,它说 concatAll 在开始下一个之前等待每个内部可观察对象完成。

    of(files.map(file => this.fileUploadService.upload(file))
      .pipe(concatAll())
      .subscribe(res => {
          /* do whatever */
      });
    

    或者你可以这样做:

    async function doUploadsSequentially(files: File[]): Promise<void> {
       files.map(async function(file: File) {
          const res = await this.uploadService.upload(file).pipe(toPromise()); 
       }
    }
    

    当然,您需要在每次上传后进行一些错误处理以及您需要执行的任何其他逻辑。我没有对此进行测试,而且我不是 rxjs 向导,因此可能需要进行一些调整。

    【讨论】:

    • 感谢您的帮助,concatAll 正是我想要的。如果可以帮助其他人,我稍后会添加代码。需要重构
    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多