Combine multiple observobserv observ observ observ observRequests from the FileReader into an array

As I work on developing a filedrop platform, I encountered an issue related to reading Blob files from the FileReader API. The code flow involves obtaining files from the user through the upload service as an observable array and converting them into base64 strings for display in the browser.

Code Snippet:

async getFileList(files: File[]) {
    let src!: IStoryFile[];
    for (const f of files) {
        const blob = await this.readFileBlob(f)
        src = [{ file: f, src: blob }]
    }
    this.uploadSrv.setFilesUpload(src);
}

readFileBlob(file: File): Promise<any> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onloadend = (e) => {
            resolve(reader.result)
        }
        reader.readAsDataURL(file)
    })
}

Once each file has been handled in the foreach loop, a next action is taken to pass the final array to the service, which then provides the data for the *ngFor | async loop in the DOM:

protected files$!: Observable<IStoryFile[]>;
...
this.files$ = this.uploadSrv.getFilesUpload$()
      .pipe(
        tap(val => console.log(val)),
      )

Current Results: The function outputs the length of the array containing Observable values.

Expected Results: The function should output a single array of objects adhering to the specified interface:

export interface IStoryFile {
  file: File;
  src?: string | ArrayBuffer | null;
}

Answer №1

Instead of repeatedly reinitializing src within the for-of loop, consider using the push method to add new objects.

  async getFileList(files: File[]) {
    let src!: IStoryFile[] = []; // Start with empty array
    for (const file of files) {
      const blob = await this.readFileBlob(file);
      src.push({ file: file, src: blob }); // Add new object to array
    }
    this.uploadSrv.setFilesUpload(src);
  }

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

Tips for managing multiple projects in Angular 7 simultaneously

Our team is currently working on an application with two separate workspaces. One workspace serves as the main project while the other is exported as a module to our private npm repository. To access this module, we retrieve it through our package.json f ...

Implementing multer diskStorage with Typescript

I'm currently in the process of converting a node.js server to TypeScript. Here is what my function looks like in Node: const storage = multer.diskStorage({ destination: function (req, file, cb) { const dir = './uploads/'; ...

Using TypeScript with makeStyles - how to effectively pass props for styling purposes

Currently, I'm using Material-UI's makeStyles feature in conjunction with TypeScript. After stumbling upon a solution that actually works, here is the snippet of code: export interface StyleProps { md?: any; } const useStyles = makeStyles< ...

How can I use Angular to change the background color of an element with the tag "li

I am working on a to do app using Angular. The data for the app is sourced from https://jsonplaceholder.typicode.com/todos. My goal is to have the background color of a "li" change when the Done button is pressed. Can anyone help me with implementing this ...

Create a unique TypeScript constant to be mocked in each Jest test

Having difficulty mocking a constant with Jest on a per test basis. Currently, my mock is "static" and cannot be customized for each test individually. Code: // allowList.ts export const ALLOW_LIST = { '1234': true }; // listUtil.ts import { ...

Using the async pipe with Angular observables

I am currently working on my first Angular application and I am facing some challenges with observables. In my HTML tag, I have the following code snippet: <mwl-calendar-month-view *ngSwitchCase="'month'" [viewDate]="v ...

Issue with Datepicker validation in Angular 5 and Angular Material

I have implemented the most recent version of Angular and Angular Material. I am facing an issue with a datepicker where the validation requirements are not being met as expected. The documentation states that the required attribute should work by default, ...

Develop a tailor-made application using Angular-Cli

In a past project using Angular 5, I utilized Grunt to create custom components and assets tailored for my clients. This involved having both a src/ folder for basic components and a clients/ folder specifically dedicated to client-specific customization. ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...

Top technique for storing a 2D array into a MongoDb database

I'm looking for the best way to store a large 2D array that I have generated. I'm considering converting this 2D array to a JSON format and then saving it using Mongoose. Is there a way to efficiently convert this data back and forth considering ...

Using Angular service within InnerHTML functions

Within my Angular 10 application, I am utilizing innerHtml to display some content that includes anchor links. My goal is to trigger a function every time a link is clicked, which will then invoke an Angular service. In the code snippet below, I am attac ...

Error Message: "Encountered an Issue with Angular Dynamic

I am currently experimenting with a small reference application to explore the concept of dynamically injecting components into another component in order to display content on a page. Recently, I encountered an error related to the ViewContainerRef object ...

Angular 2 Kendo Grid Group Collapse

When attempting to collapse grouped rows upon button click, I encountered some challenges with the code. The following snippets illustrate my attempts: @ViewChild(GridComponent) grid: GridComponent; close(); { for (let m = 0; m < 5; m ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

Module ng2-img-tools encountered a metadata version mismatch error

Encountering an error while trying to utilize the ng2-img-tools package in conjunction with Angular4. The specific error message is: ERROR in Metadata version mismatch for module ~/client/node_modules/ng2-img-tools/dist/ng2-img-tools.d.ts, found version 4 ...

In Angular 2+, what is the best method for displaying elements based on whether the user is logged in or logged out?

Struggling with the transition from AngularJS to Angular 2+ for my app. I'm facing challenges implementing a simple feature that was previously effortless in AngularJS. The issue is with the top navigation - I want it to display a LOG IN button when ...

How can I create an SVG node on a ref using TypeScript?

I'm currently working on creating a reference in React with TypeScript: class BarChart extends Component { private node: React.RefObject<SVGSVGElement | null>; constructor(props) { super(props); this.node = React.createRef(); } .. ...

The declaration of 'exports' is not recognized within the ES module scope

I started a new nest js project using the command below. nest new project-name Then, I tried to import the following module from nuxt3: import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge'; However, I encountered th ...

Mapbox popup not displaying CSS properly

I am trying to customize the appearance of the popup in my mapbox using a unique CSS style. However, it seems that the CSS is not being applied to the popup. var popup=new mapbox.Popup({offset:25,closeButton:false,closeOnMove:true,className:'pop-up& ...

What is the best way to show the current date and time in an Angular template while ensuring it stays up to

I'm looking to showcase the current date and time in my angular template, and have it automatically refresh when the time changes. The desired application LOOKS as follows: This snippet is from my .html template: <div class="top-right pull-right ...