【问题标题】:add an additional parameter to an observable response向可观察响应添加附加参数
【发布时间】:2019-11-21 16:52:21
【问题描述】:

我有以下代码

    getFileAsync(fieldFiles: Array<FileFields>): Observable<Array<UploadFile>> {
        const files = Array<UploadFile>();
        const downloads = Array<Observable<any>>();
        fieldFiles.forEach(file => {
            downloads.push(FileHelper.downloadFile(file.file_id));
        });
        forkJoin(downloads).subscribe({
            next: filesData => {
                console.log(filesData)
                fieldFiles.forEach((file, index) => {
                    const fileData = filesData[index];
                    files.push({
                        uid: file.file_id,
                        name: file.filename,
                        url: fileData ? window.URL.createObjectURL(new Blob([fileData.data], {type: file.contentType})) : require('../../../assets/images/file.png'),
                        size: file.size,
                        type: file.contentType,
                    })
                })
            },
            error: () => {}
        });
    }

基本上,我有一个文件列表,我想一个一个下载:

我使用FileHelper.downloadFile,它返回一个http observable

        const downloads = Array<Observable<any>>();
        fieldFiles.forEach(file => {
            downloads.push(FileHelper.downloadFile(file.file_id));
        });

然后,我使用 forkJoin(downloads) 发送请求并获取响应。 但是,我想改用concatMap 并一个一个下载文件。

但问题是,http 请求不返回文件 id,所以我需要一种方法来知道当前正在加载的 id 是什么。像这样:

        const downloads = Array<Observable<any>>();
        fieldFiles.forEach(file => {
            const fileId = file.file_id;
            downloads.push(FileHelper.downloadFile(fileId));
        });
        concatMap(downloads).subscribe({
            next: (filesData, fileId) => {}

有没有办法添加这个变量并将其“绑定”到 http 请求的 observable ?

【问题讨论】:

    标签: javascript typescript rxjs observable


    【解决方案1】:

    您可以使用 observable 的 map 操作符将其转换为一个同时具有 id 和 data 的对象。像这样的:

        const downloads = Array<Observable<any>>();
        fieldFiles.forEach(file => {
            const fileId = file.file_id;
            downloads.push(FileHelper.downloadFile(fileId).map((x) => ({ id: fileId, data: x}));
        });
        concatMap(downloads).subscribe({
            next: (x) => { 
               // x.data 
               // x.id
             });
    

    【讨论】:

    • 感谢您的回复,它看起来正是我想要的,但是当我尝试您的代码时我有Property 'map' does not exist on type 'Observable&lt;any&gt;'
    • 好的,我用了downloadsObs.push(FileHelper.downloadFile(file.file_id).pipe(map((resp) =&gt; ({ fileId: file.file_id, response: resp}))));,看起来不错,谢谢
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多