Executing operations takes precedence over the process of interpreting image information

I've been using Angular and I'm dealing with a function that handles image input.

While working with the inserted images, I extract information such as name and size. However, my issue arises when I need to upload an image (to determine its height and width) because the upload function is executing before the function that retrieves the image information.

This results in 'undefined' values for width and height.

The upload function seems to be triggering before image.onload gets called :(

Any idea why this might be happening?

Component.ts


detectFiles(event) {

    if (files.length < 8) {
      for (let index = 0; index < files.length; index++) {

        this.items.push(item);
        const reader = new FileReader();
        reader.onload = (e: any) => {
          item.url = e.target.result;
          const image = new Image();
          image.src = e.target.result;
          image.onload = function () {
            item.sizeH = image.width;
          };

        }
        formData.append('file', files[index]);
        reader.readAsDataURL(files[index]);
      }
    }
  }

Answer №1

Explaining the situation is quite simple. Javascript operates in a sequential manner, but it can be difficult to determine which command comes first in the stack in your particular scenario.

The code below indicates that when a certain event triggers the onload function, it should be executed.

      image.onload = function () {
        item.sizeH = image.width;
        item.sizeV = image.height;
        self.sizeH = item.sizeH;
        self.sizeV = item.sizeV;
      };

Before anyone calls this function, you proceed with the upload using the subscribe method. It is common for the sequential commands to be executed first.

If the upload was done within the onload function, then there would not be an issue.

      image.onload = function () {
        item.sizeH = image.width;
        item.sizeV = image.height;
        self.sizeH = item.sizeH;
        self.sizeV = item.sizeV;
        // upload logic here.
      };

Answer №2

Maybe the issue lies in

 reader.onload = (e: any) => {
      item.url = e.target.result;
      const image = new Image();
      image.src = e.target.result;
      image.onload = function () {
        item.sizeH = image.width;
        item.sizeV = image.height;
        self.sizeH = item.sizeH;
        self.sizeV = item.sizeV;
      };

You could try this approach to see if it makes a difference

reader.onload = () => {
 // Your code goes here
}

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

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Guide on implementing an enum as a type by attaching it to a class as a static variable

// file1.ts enum Variant { Success = 'success', Error = 'error', } export class Example { static Variant = Variant; } // file2.ts import { Example } from './file1'; type Props = { variant: Example.Variant; // TS2 ...

How to properly import a new typings file in Typescript for Node.js applications?

I'm feeling quite overwhelmed by the different methods available for importing a Typings file. It seems like there are numerous ways to accomplish this task. Currently, I am working on a nodejs program. I successfully installed momentJS through typi ...

How do I determine if a child component is in a dirty state within CanDeactivateGuard when dealing with multiple form tags?

Currently, I am utilizing a template driven form within my project. The parent component that I am working on is as follows: parent.component.html <tab> <form> <input></input> <button></button> </form ...

Troubleshoot syntax issue within a massive Eval expression

We are experiencing an issue with our Angular application that is working perfectly in Chrome, but encountering a syntax error in an Eval statement when running in Internet Explorer. Is there a way to pinpoint the exact line within the Eval statement cau ...

Ensuring consistency in property formatting strategies

I'm curious if there exists a way to specify the format that an interface property should adhere to. For instance: interface User { age?: number, name: string, birthdate: string // must be in 'YYYY-MM-DD' format } I came across de ...

What is the best way to expand upon the declaration file of another module?

I have encountered a problem with declaration files in my AdonisJS project. The IoC container in Adonis utilizes ES6 import loader hooks to resolve dependencies. For instance, when importing the User model, it would appear as follows: import User from ...

Display loader during data retrieval in Angular 2

In my loader.component.ts file, I have defined the selector as <app-loader>. The <app-loader> tag is located in the main-component.html file and is displaying correctly. <app-loader *ngIf="!showLoader === true"> I want the loader to on ...

Definitions for Typescript types that describe a custom hook responsible for fetching a specific part of the Redux state

I've created a custom hook called useReduxState to fetch a specific piece of state from Redux like so: const STATE_A = useReduxState("STATE_A"); Now, I'm running into issues when trying to integrate Typescript. These are the types I a ...

The inner workings of Angular 2: uncovering what occurs once we navigate to http://localhost:4200 on our browser

Could anyone provide a detailed explanation of the startup process for an Angular2 project? For example, after creating a sample project using Angular CLI: Run 'ng new my-test-app' Navigate to 'cd my-test-app' Start the server with & ...

Leveraging the (click) event within an HTML template to manage a [hidden] element located in a different template using Angular 2

Within my project, I have two TypeScript files, each containing HTML templates inside the @Component. In one of the templates, there are info cards that can be collapsed or expanded using [hidden]="collapsed". The following function is present in both file ...

Challenges encountered while using TypeScript to implement the CSS breakpoint mixin

I attempted to replicate the breakpoint mixin functionality described at using TypeScript, but I am having trouble correctly typing the function. import { css } from 'styled-components'; import { breakpoints } from './_variables'; exp ...

Interact with DOM elements and manipulate TypeScript data

I am looking to display a list of IDs by fetching them from my database. Within my ngfor loop, I have included a child component. Is there a way to access each ID within each child component? I would like to retrieve the value of "GameToDisplay.key" in pl ...

What are the best practices for utilizing fetch() to retrieve data from a web API effectively?

Is there a way to store stock data in stockData and display it in the console upon form submission? Upon submitting the form, I only receive undefined. I suspect this may be due to a delay in fetching data from the API (but not certain). How can I resol ...

What is the best way to pass createdDt and updatedDat values in an Angular form without displaying them on the template?

I am working on a message creation form in Angular where I need to include createdDt and updatedDt as hidden values. These values should not be visible in the template. I want to automatically set the current date and time for both createdDt and updatedD ...

Unable to locate 'http' in error handling service for Angular 6

My current project involves creating an Error Handling Service for an Angular 6 Application using the HTTP Interceptor. The main goal of this service is to capture any HTTP errors and provide corresponding error codes. However, my lack of familiarity with ...

Encountered a problem while executing an Angular project in Visual Studio Code

Encountering errors while trying to run a freshly created Angular project within Visual Studio Code Error: Unable to find module - Error: Unable to resolve 'C:/C#/Angular/AngularApp/src/app/app.component.css?ngResource' in 'C:\C#\A ...

Executing 'npx tsc --version' displays a distinct TypeScript version within the virtual environment

I need to run npx tsc on my project in both my host and guest operating systems. However, the guest OS is using an older version of tsc that I cannot identify. Here is my setup: Host OS: Windows 10 Guest OS: Debian 9 I am using VirtualBox with the "shar ...

The ButtonProps module is not compatible with the Button component within the same package

When working with Reactstrap, Typescript, and typings from @types/reactstrap, I encountered an issue while using the Button component in a Higher Order Component (HOC) that requires explicit reference to the ButtonProps type. Below is the code snippet: i ...

The successful operation of 'Ionic serve --lab' may involve the need to manually save the app.module

We are currently working on an Ionic project that consists of several pages and a single custom provider named request.ts. The issue we are facing is that whenever we launch it using the command ionic serve --lab, the compilation fails (with the error poin ...