Having trouble retrieving a value from the img.onload event handler. A 'boolean' type error is being thrown, indicating it cannot be assigned to type '(this: GlobalEventHandlers, ev: Event) => any'

In my Angular application, I have implemented a method that verifies the size and dimensions of an image file and returns either false or true based on the validation result. Below is the code snippet for this function:

checkFileValidity(file: any, multiple: boolean): any {
    const reader = new FileReader();
    const img = new Image();
    img.src = window.URL.createObjectURL(file);
    reader.readAsDataURL(file);
    return img.onload = function () {
      const tableError = []
      const width = img.width;
      const height = img.height;
      console.log(img.width);
      console.log(img.height);
      if (file.size > 3000000) {
        console.log('size');
        tableError.push('size');
      }
      if (width < 1919 || height < 1079) {
        console.log('dimension');
        tableError.push('dimension');
      }
      if (tableError.length > 0 && !multiple) {
        return false;
      } else if (tableError.length > 0) {
        console.log('size+dimension');
        return false;
      }
      return true;
    }()
  }

I encountered an error at the line "return img.onload = function () {". How can I resolve this issue?

Answer №1

When you place the parentheses () immediately after the closing bracket } of your function assigned to img.onload, you are causing it to be invoked right away. As a result, the function executes and returns either true or false. Essentially, what is happening in this scenario is:

return img.onload = true;

This leads to an error being triggered. To resolve this issue, refrain from including the invoking parentheses () following the function body.

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 ag-Grid cellDoubleClicked event seems to be triggered twice when the cell is double clicked quickly, but functions correctly when double clicking at a slower

Currently, I am facing an issue in my Angular 8 project while using Ag-grid. The problem arises when I try to handle the double click event in ag-grid. Whenever the cellDoubleClicked event is triggered, a method is called twice if I quickly double click on ...

Receiving the error notification from a 400 Bad Request

I'm having trouble showing the errors returned from an API on my Sign up form when a user submits invalid data. You can check out the error response in the console here: console ss This is my approach in RegisterComponent.ts: onSubmit() { this.u ...

Visual Studio Code encountering an NPM error

I am encountering errors when I try to run Visual Studio. The specific errors are: npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'F:\AngularNew\package.json' ...

I have set up a custom ag-grid three times within a single component, however, only the first instance is properly initialized while the other two instances are not initialized

I have developed a custom ag-grid for reusability in my project. Initially, when I initialize the custom ag-grid in one component, it works perfectly as shown below: example.html <html> <body> <input type="text"> <md-app-aggrid [c ...

showing pop-up notification in Angular

I am utilizing the ngx-alert service to show an error message if the supplied credentials do not match any user account in my database. This is my current process: if (this.check.data.length == 0) { this.alert.danger('User does not exist' ...

tips for utilizing a variable for inferring an object in typescript

In my current code, I have the following working implementation: type ParamType = { a: string, b: string } | { c: string } if ('a' in params) { doSomethingA(params) } else { doSomethingC(params) } The functions doSomethingA and doSomething ...

An effective way to extract targeted information from an array of objects using Typescript

I'm having trouble extracting the IDs from the selected items in my PrimeNG DataTable. Despite searching on Google, I couldn't find much information about the error I'm encountering... ERROR in C:/Users/*****/Documents/Octopus/Octopus 2.0/s ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

Steps to arrange by the number of rows in ag grid

I've been experimenting with the rows group feature in ag-grid, But I'm curious if it's feasible to sort the group column based on the number of rows within each group? Here is an example of what I am trying to achieve: ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Error in TypeScript: Module 'stytch' and its corresponding type declarations could not be located. (Error code: ts(2307))

I'm currently developing a Next.js application and encountering an issue while attempting to import the 'stytch' module in TypeScript. The problem arises when TypeScript is unable to locate the module or its type declarations, resulting in t ...

Angular 2 can efficiently generate multiple HTTP requests simultaneously from a single HTTP request

Backend API's: url: [ { "name": "ABC", "occupation": "Student", "address_url": "http://www.sample.com/address/person=hgjgjgyyfhg" }, { "name": "ABC1", "occupation": "Carpenter", "address ...

Storing information in a FormArray within an Angular reactive form

I'm facing a challenge with setting an array of data from an API to a FormGroup that contains a form array. It seems like I'm missing something in the process. Form this.blog = this.fb.group({ title: ['', Validators.required], ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...

The page has been updated following a refresh

I'm currently working on developing an Instagram-inspired platform using Angular 6, but I've run into a puzzling issue. When I refresh the page in my home component, everything reloads correctly and displays all my posts as expected. However, if ...

Tips for effectively handling Dependency Injection when interfacing with a service that requires a component

I oversee a project in Angular that follows this specific architecture: ├── media └── src ├── app │   ├── core <-- services folder inside │   ├── data │   ├── layout │  ...

Is there a way to include values in the body of an HTTP GET request using Angular?

I've created a function in my service that looks like this: /** * Retrieve all data * @param sendSelectedValues string */ getAllActPlanBalanceYearData(sendSelectedValues: any): Observable<any> { const url = `/yearlyvalues/act-and ...

Encapsulate the HTTP request within a common function for reus

My rest-provider service handles all of my http calls, but I've noticed that each function is repeating a lot of the same http code. It seems like I should create a shared function to avoid this repetition and make it easier to update in the future. ...

TypeScript failing to correctly deduce the interface from the property

Dealing with TypeScript, I constantly encounter the same "challenge" where I have a list of objects and each object has different properties based on its type. For instance: const widgets = [ {type: 'chart', chartType: 'line'}, {typ ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...