When attempting to access an array element by index, it is returning as null

I have a script that extracts the dimensions of an image:

  getImageDimensions(file: File): Number[]{

    let dimensions : Number[] = [];
    let _URL = window.URL || window.webkitURL;
    let img, file;
    file = fileUploaded;
    img = new Image();
    img.onload = function() {
      dimensions.push(Number(this.width));
      dimensions.push(Number(this.height));
    };
    img.onerror = function() {
      //alert( "not a valid file: " + file.type);
    };
    img.src = _URL.createObjectURL(file);

    return dimensions;
  }

I call this function from another module:

  let imageSize = this.utilService.getImageDimensions(this.image[0]);
  console.log(imageSize);
  console.log(imageSize.length);
  console.log(imageSize[0]);
  if(Number(imageSize[0]) !== 512 || Number(imageSize[1]) !== 512) {
    this.notifications.create(
      'Error',
      'Image resolution must be 512x512',
      NotificationType.Error,
      { theClass: 'outline primary', timeOut: 6000, showProgressBar: false }
    );
    return;
  }

The first console log outputs the array correctly, but the length is 0 and when trying to access elements it returns undefined:

https://i.sstatic.net/BffUG.png

Answer №1

It's important to note that the function getImageSize operates asynchronously. To properly utilize it, you must first convert it into a promise. Here is an example:

  getSizeOfFile(fileToCheck: File) {
    return new Promise((resolve, reject) => {
      const dimensions: number[] = [];
      const _URL = window.URL || window.webkitURL;
      let file, img;
      file = fileToCheck;
      img = new Image();
      img.onload = function() {
        dimensions.push(Number(this.width));
        dimensions.push(Number(this.height));

        resolve(dimensions);
      };
      img.onerror = function() {
        reject('invalid file type: ' + file.type);
      };
      img.src = _URL.createObjectURL(file);
    });
  }

To implement this in another service, simply use the await keyword like so:

let fileSize = await this.someService.getSizeOfFile(this.file[0]) ;

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 method for obtaining the union type of interface values (including string enums)?

How can I achieve the following ? Given : enum FooEnum1 { Foo = "foo", }; enum FooEnum2 { Foo = 1, }; interface FooInterface { foo1 : FooEnum1, foo2 : FooEnum2, foo3 : string, foo4 : number, }; I am interested in cre ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

Version 5 of angularfie2 is encountering an issue where the type 'Observable<{}[]>' cannot be assigned to the type 'Observable<any[]>'

Encountering an error while using angularfire2 version 5: The error reads: "Type 'Observable<{}[]>' is not assignable to type Observable < any [] >." Code snippet: exercisesList$: Observable <any[]>; ionViewDidLoad() { ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

The variable "this.data" in Angular 2 is experiencing the issue

I am attempting to access and read the information stored in my JSON file using my "GetJsonService". app.component.ts: data: any; constructor(private jsonService: GetJsonService) {} ngOnInit() { this.getRecords(); console.log(this.data); } get ...

Struggling with object type casting in Typescript

Having issues with casting objects from an HTTP API response to Typescript. I am trying to cast the json data to a Typescript object using the "as" keyword or <Type >, but it's not working as expected. r.forEach(entry => { entry.creatio ...

Modifying the value of a React input component is restricted when the "value" field is utilized

I'm currently utilizing material-UI in my React application. I am facing a challenge where I need to remove the value in an input field by clicking on another component. The issue arises when using the OutlinedInput component with a specified value. ...

Working with an array of objects with varying shapes and validating them

I have dedicated quite a bit of time to this task and would greatly appreciate some assistance. I am in need of a component (a function) that can accept an array of objects while also validating the properties of these objects. Here are the interfaces and ...

The application is unable to load due to a console error showing that the endpoint is unreachable

Recently, I made an upgrade from Angular 5 to 7 while still keeping rxjs-compat in place. Initially, the application was running smoothly with no issues. However, we eventually decided to remove rxjs-compat and make the necessary changes. This is when we e ...

The definition of "regeneratorRuntime" is missing in the rete.js library

After encountering a problem, I managed to find a potential solution. My current challenge involves trying to implement Rete.js in Next.js while using Typescript. The specific error message that's appearing is: regeneratorRuntime is not defined Be ...

The function of getTime is not available for use

I assigned the date_work property to a Date data type. However, when I check the data type using the command console.log(typeof master.date_work), it shows as a string for some reason. This causes an error when using the getTime() function. How can I conve ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

Parent method instantiating child class instance

My code includes a parent class and a child class, with the parent class containing a modify function: const modify = (data) => { const newData = data // changes newData in some way return newData } class Parent { constructor(data) { this.d ...

Struggling to set up a Jest testing module for a NestJs service. Encountering an issue where Nest is unable to resolve dependencies of the UsersService, specifically the Config

Greetings, fellow developers! I am excited to ask my first set of questions on stackoverflow :) Currently, I am working on a test/learning application to enhance my skills in NestJS and Vue. During the implementation of server-side unit tests using Jest, ...

Encountering a 500 error code while attempting to send a post request using Angular

Whenever I attempt to send a post request to Django server, I encounter a 500 (Internal Server Error) response. Interestingly, the get and put requests work flawlessly on the same server where Django is connected to PostgreSQL database. Here is a snippet ...

Angular - Creating validations for numeric input fields within reactive forms to ensure values fall within a designated range

One issue I am facing in my Angular form is with a numeric input field. The requirement is to set the minimum value as 3 and the maximum value as 10. However, upon loading the form, the default value should be 0. Users are expected to enter values ranging ...

Creating a redux store with an object using typescript: A step-by-step guide

Having recently started using Redux and Typescript, I'm encountering an error where the store is refusing to accept the reducer when working with objects. let store = createStore(counter); //error on counter Could this be due to an incorrect type set ...

Utilizing Consistent Styles Across Multiple Components within an Angular 2 Application

In my Angular 2 app, I have some CSS rules that are shared among multiple components. I don't want to duplicate these rules in each component's styles. Currently, I am considering two approaches: Storing common CSS rules in a static CSS file an ...

Discover the type of generic keyof in TypeScript

My types implementation is structured as follows: type GenericType<T, K extends keyof T = keyof T> = { name: K; params: T[K] } type Params = { a: 1; b: 2; } const test: GenericType<Params> = { name: "a", params: 2 } ...