Include an extra condition in an observable output

I am working with the following code snippet:

    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: () => {}
        });
    }

Essentially, I have a list of files that I want to download one by one:

I am using FileHelper.downloadFile which returns an HTTP observable.

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

Afterwards, I use forkJoin(downloads) to make the request and receive the responses. However, I am interested in using concatMap instead to download the files sequentially.

The challenge is that the HTTP request does not return the file ID, so I need a way to track which file ID is currently being downloaded. For example:

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

Is there a method to include this variable and associate it with the observable of the HTTP request?

Answer №1

If you want to convert an observable into an object containing both the id and data, you can utilize the map operator. Below is an example of how you can achieve this:

    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) => { 
           // access x.data 
           // access x.id
         });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Have I got it all wrong with the way Controllers communicate with Services and how I conduct unit testing?

Currently, I am in the process of developing an AngularJS application and I want to ensure it follows best practices. When making external API calls using either $resource or $http, I always do this within a separate Service or Factory. However, I am unsur ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Ways to identify when a jQuery ajax request has finished executing?

Currently, I have a dropdown menu of countries that is populated using a jQuery ajax call. The issue I am facing is determining when the call is complete so that I can correctly select a country afterwards. Any function I call after the ajax function is tr ...

In Safari, the scrollbar appears on top of any overlays, popups, and modals

On my webpage, I have a div with the CSS property overflow-y: scroll. The page also features several popup modals and overlays. Strangely, the scrollbar of the div appears on top of these overlays instead of behind them. I attempted to resolve this issue b ...

Error occurred: Undefined module imported

CounterDisplay.js import React from 'react'; const CounterDisplay = <div> <h1>{this.state.counter}</h1> <button onClick={this.handleDecrement}>-</button> <button onClick={this.handleIncrement}>+ ...

Encountered an Unhandled Runtime Error in NextJs: Invalid Element Type

Attempting to build an Instagram clone following a YouTube tutorial from a year ago has led to various errors arising from nextjs14. I have managed to resolve all of them except for one particular issue: Error: Element type is invalid - expected a string ...

Adjust the size of a division based on the width of the screen using JavaScript

Is there a way to create a JavaScript function that dynamically adjusts the size of a div, image, or padding based on the screen width without using CSS? I am specifically interested in adjusting the padding of a div element. Here is a sample code snippet ...

What are the steps to reset the default global path for npm on an Ubuntu system?

After altering the default global path for the node-sass package, I noticed that other globally installed packages are not working as expected. Any suggestions on how to resolve this issue? ...

Tips for developing a sophisticated HTML quiz

I have spent countless hours perfecting this quiz. I have successfully created a quiz that reveals solutions at the end, but I want to take it one step further. I envision the answers appearing after each incorrect response from the user, and no answer sho ...

The two divs are positioned on top of one another, with the link in the bottom div being unclickable

I am trying to create a unique effect where a tile divides into two on hover, with each tile acting as an individual link. Additionally, I want the background color of the tiles to change on hover. To achieve this, I have stacked two divs (toptile and bot ...

Creating dynamic forms in Vue using v-for

I'm currently experimenting with creating dynamic form fields using v-for and vuex. My approach involves nesting a v-for inside another v-for. The process of adding new form fields works smoothly, but I encountered an issue when attempting to delete t ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

Unable to upload files using Jquery.form (3.51.0-2014.06.20) in IE9 within a Sharepoint application

Before diving into this issue, I want to clarify that I have thoroughly researched similar problems on Stack Overflow and other forums related to jQuery form upload problems. However, I am confident that the issue I am experiencing is unique. The problem ...

What is the best way to create a circular to square gradient and save it within a two-dimensional array?

Can anyone guide me on creating a circle/square gradient and storing the data in a 2D array? I want to incorporate this gradient with simplex-noise to develop a procedural island by subtracting the gradient from the generated noise. Here are some visual re ...

"Enhance user experience with Angular Material: Popup Windows that preserve functionality in the original window while staying vibrant and accessible

Exploring Angular Material Dialog and other Popup Window Components for a project. Making progress but facing some challenges. Here are the requirements: a) The original screen should not be grayed out, b) Users should be able to interact with the windo ...

Incorporate JavaScript Library into StencilJs Using TypeScript

Recently, I decided to incorporate a JavaScript library called Particles.js into my project. The process involved importing it and initializing it within my component: import { Component, h } from '@stencil/core'; import * as particlesJS from &a ...

Using Angular to include a forward slash "/" in the text input for a date field

Hello everyone, I am a newcomer to AngularJS and I am looking to insert slashes in an input type text element. I prefer not to rely on external packages like angular-ui or input type Date. My goal is to have the format mm/dd/yyyy automatically applied as ...

Ways to retrieve element values in JavaScript without relying on IDs

Imagine for a moment that I had the subsequent code: <div class="post"> <h2 itemprop="name"> <a href="http://www.example.com">The Post Title</a> </h2> <div class="details"> <span> <em class="date" ...

Using Karma-Jasmine to Import Spy without anyImplicitAny

If I include the configuration setting noImplicitAny in the tsconfig.json file of my Angular 4+ project: "noImplicitAny": true, ...and then try to import and use Spy in a unit test: import { Spy } from "karma-jasmine"; I encounter this console error wh ...

What is the best way to incorporate progress updates into a rendered jade page?

I am currently working on a small express.js application with a form. When the form is submitted, it triggers a python script that takes approximately 5 minutes to run and outputs messages to the console while it is running. At the moment, I am able to cal ...