What is the reason for receiving the property body.__zone_symbol__value within a promise in Angular 16?

Here's a simple method to locate any file type key in a formdata object and save it in an indexed database.

First, I save the information like this:

const data = item instanceof FormData ? await this.idb.serializeRequestBody(item) : item;

The 'items' variable can be either FormData or JSON(string).

With these functions, I convert my file to base64 to make it readable in an img tag:

public serializeRequestBody(body: FormData): any {
  try {

    const data: any = {};

    body.forEach(async (value, key) => {
      if (value instanceof File) {
        await this.fileToBase64(value).then((base64) => {
          data[key] = base64;
        });
      } else {
        data[key] = value;
      }
    });
    return data;

  } catch (error) {
    console.error('Error serializing request body:', error);
    throw error;
  }
}

private async fileToBase64(file: File): Promise<string> {
  try {
    const reader = new FileReader();
    return new Promise<string>((resolve, reject) => {
      reader.readAsDataURL(file);
      reader.onload = () => {
        resolve(reader.result as string);
      };
      reader.onerror = (error) => {
        reject(error);
      };
    });
  } catch (error) {
    console.error('Error converting file to Base64:', error);
    throw error;
   }
}

However, I encountered this issue:

error image

I included it as an image because the URL is too lengthy. I have tried utilizing promises, tryCatch, searched for other solutions, but haven't found one that works for me.

I am hopeful that someone can provide guidance!

Answer №1

Handling asynchronous operations in forEach can be tricky.

To address this, consider using a for loop or Promise.all method to manage async tasks within the loop.

let resultData: any = {};
let promiseArray: Promise<void>[] = [];

data.forEach((element, index) => {
  if (element instanceof File) {
    promiseArray.push(
      this.convertFileToBase64(element).then((base64String) => {
        resultData[index] = base64String;
      })
    );
  } else {
    resultData[index] = element;
  }
});

await Promise.all(promiseArray);

return resultData;

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

The performance of the Ionic iOS app leaves much to be desired compared to its speedy counterpart

I have developed a shopping cart app using Ionic framework, and it is almost complete. When I try to build the app using the following command: ionic cordova build --release --prod --verbose XXXXX where XXXXX can be either ios or android. Building for An ...

Setting up a reverse proxy for Karma during Angular testing is essential for ensuring that

When developing my application, I rely on a backend web service for API calls. I have successfully configured a reverse proxy for the Angular CLI server using the command ng serve --proxy-config proxy.config.json. Everything works fine in this setup. Howe ...

What is the best way to consolidate promises produced by asynchronous functions in a Node.js stream callback?

In my Node.js TypeScript program, I am facing the challenge of parsing large CSV files line by line and asynchronously processing each line. Specifically, I require a function that will: Open a CSV file. Convert the next line into an object. (Ideally) Ga ...

Managing null values in RxJS map function

I'm facing a scenario where my Angular service retrieves values from an HTTP GET request and maps them to an Observable object of a specific type. Sometimes, one of the properties has a string value, while other times it's null, which I want to d ...

How to automatically redirect in Angular 2 by utilizing router.navigate

router.navigate() seems to be working correctly in one scenario, but in another case it is redirecting to the home page unexpectedly. app.module.ts const appRoutes: Routes = [ { path: 'news/:urlLink', component: ArticlereaderComponent }, ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...

Reactjs and Typescript - A Powerful Duo

I'm working on creating a Searchbar that will display the author ID and picture based on user input, but I'm encountering an error in my code: any Property 'toLowerCase' does not exist on type 'never' import { useEffect, us ...

How to eliminate certain elements from the DOM in Angular 5

I'm facing a minor issue in my Angular/Typescript project that I can't seem to resolve. I am still new to these technologies and struggling with removing certain DOM elements. The content is auto-generated with specific CSS classes, and unfortuna ...

Begin a hyperlink element with an onclick function that opens in a separate browser tab

I am having an issue with opening a link in a new tab. I have a button with an anchor tag inside that has a click event bound to it. Despite using target="_blank", the link still opens in the same tab. <button class="btn btn-primary"><a target ...

The HTTP stream was mistakenly sent out twice instead of just once

I can't figure out why my code is acting up. In the service, I have the following: updateCollection(){ var updateStream = this._http.get('someApi') .map((res)=>{ return res.json(); }) updateStream.sub ...

Issue with sizing of bar chart in Angular Chart.js - width not adjusting accurately

Currently, I am working with Angular 12 and the latest version of Chart.js for my project. I am attempting to create a bar chart with a smaller width by using barPercentage: 0.4, but it seems like this code is not being applied correctly. Does anyone have ...

Encountering the error "tsx is not defined" during a Jest test in a React/TypeScript project

I'm currently working on implementing Jest tests within a React project that has enforced TypeScript settings. In a simple test.tsx file located in the test folder, I have the following code: import React from 'react'; describe('Test& ...

How can I ensure that only the most recent value is sent in an RxJS Subject, clearing out any previous

In my Angular application, I have a grid with buttons in each row that open respective popups when clicked. To handle this functionality, I created a service with a property called popupEventSubject$, which is a BehaviourSubject. The problem I am encounte ...

Create the HTTP POST request body using an object in readiness for submission

When sending the body of an http post request in Angular, I typically use the following approach: let requestBody: String = ""; //dataObject is the object containing form values to send for (let key in dataObject) { if (dataObject[key]) { ...

Typescript error: The 'new' expression is missing a construct signature for its target, resulting in an implicit 'any' type

Here is a code snippet optimized for displaying custom errors in Chrome Devtools, Node.js, and other platforms. The inspiration for this came from this specific answer on StackOverflow. function CustomErr (message) { var err = new Error(message) Objec ...

Enhancing Code: Eliminate Duplicates from an Array

I have a code that removes duplicates from an array, but I believe it could be improved for better elegance. Any suggestions? Interface Definition export interface SomeClass { version: number, typeDescription: string } Test Data someClasses: SomeCla ...

Exploring the concept of destructuring function props using TypeScript

I'm having trouble running a Flatlist with typescript because it only allows an expression function with destructured props. I can't seem to figure out how to destructure with the necessary type (Suggestion). Does anyone have a solution for this? ...

Using Angular 4 to populate a form and ensure it remains untouched

Designed an update form that is pre-populated with information. I am aiming for the button to be inactive until any changes are made within the form The form group utilizes valueChanges to detect when information has been modified However, even when I u ...

Modular Angular Component

I'm currently developing a language learning application using Angular 15. With numerous pages and components featuring diverse content, I am exploring the option of allowing users to customize the font type, size, and other display settings for each ...

Consuming NATS Jetstream with multiple threads

My TypeScript application consists of multiple projects, each with its own set of microservices: server: A REST API that publishes messages to NATS for other services to update a (mongo) DB synchronizer: A process that consumes NATS messages and updates t ...