Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app.

The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPersonas(). Despite trying various approaches, the function always ends up being called as undefined and does not execute even once.

Below is the code snippet:

     subirArchivo(req: Request, res: Response) {
    var form = new IncomingForm();
    let readStream;
    var self = this;
    this.insertaPersonas('a'); // function undefined

    form.parse(req);
    form.on('file', (field: any, file: any) => {
      // Do something with the file
      // e.g. save it to the database
      // you can access it using file.path
      console.log('file', file.name); //this works
      readStream = fs.createReadStream(file.path); // this works
      // console.log(file.path); //this works
      self.insertaPersonas(file.path); //function undefined
    });
    form.on('end', () => {
      res.json();
    });
  }

For the complete class code, visit: https://pastebin.com/b8a2E3EZ

Answer №1

Seems to be a common bind issue;

class MyClass {
  other () {
    console.log('enter')
  }
  fn () {
    this.other()
  }
}

const instance = Class()
instance.fn() // works

Promise.resolve()
  .then(instance.fn.bind(instance)) // works

Promise.resolve()
  .then(instance.fn) // fails: this.other is undefined, not a function

You may want to locate where you are calling your subirArchivo function and ensure it is called as myInstance.subirArchivo(), or bind the instance beforehand, either when referencing it as

myInstance.subirArchivo.bind(myInstance)
, or in the constructor:

class UploadController {

  constructor () {
    this.subirArchivo = this.subirArchivo.bind(this)
  }

  insertaPersonas (...) { ... }
  subirArchivo () { ... this.insertaPersonas(...) ... }

}

For additional information, refer to Use of the JavaScript 'bind' method

Answer №2

It seems likely that the issue lies with the self reference. Using self=this is unnecessary due to the arrow function.

Do you know who is invoking the function subirArchivo?

I suspect that the self variable in that context may not be referring to your uploadController class.

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

Design nested divs that can be dragged within the confines of their parent div

At first, the app will include a single button called AddParent located at the top. When the user clicks the AddParent button, a parent draggable component is added to the existing component. This means that every time the button is clicked, a new parent ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

Angular.js dynamically changing ng-class based on long-polling updates to a monitored variable

Currently utilizing angular.js for my project. I am implementing long polling with a server and would like to dynamically update an element in the view, specifically one with a class of 'updated', whenever the value of build_tag is incremented. ...

I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on th ...

Using jQuery to select and animate several elements simultaneously without repeating the animation

Issue Summary (Fiddle): I'm trying to make all elements fade out simultaneously when clicked, but the current code causes the target to trigger three times resulting in three alert() calls. I want them to fade together without using a wrapper element ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

How to ensure a div within an anchor tag occupies the full width in HTML and CSS?

In my code, I am working on creating multiple small boxes with images and centered text inside. The goal is to have these boxes clickable, where clicking the image will take you to a specific link. On desktop, I want a hover effect that darkens the image b ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

Unable to access member function of Typescript class

I recently started using typescript and encountered an issue while working on a problem. I initially created the following class: export class ModuleInfoContainer extends Array<ModuleInfo> { constructor() { super(); } search(id: number) { ...

How to automatically choose the first option in a v-for loop in Vue.js

I have a loop that creates a dropdown menu from an array: <select class="form-control" v-model="compare_version" > <option v-for="(version, index) in allVersions" v-bind:value="index" v-bind: ...

Javascript - formatting numbers with decimals

This question is not related to math or operators, but rather a formatting or masking issue. I am working on creating an order form that uses Javascript to tally and display the quantity and cost of each column in separate fields. I am trying to format th ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...

The continuous rerendering of my component occurs when I use a path parameter

In my project, I am working on utilizing a path parameter as an ID to fetch data for a specific entity. To accomplish this, I have developed a custom data fetching hook that triggers whenever there is a change in the passed parameters. For obtaining the bo ...

How can we stop the parent modal from closing if the child component is not valid?

I have a main component with a modal component that takes another component as a parameter. The child modal component has some logic where I need to check if the child component is valid before closing the modal. const MainComponent: FC<IProps> => ...

Angular 2 navbar malfunctioning

I'm currently working on creating a navigation bar with images that, when clicked, navigate to specific components. Here is the code snippet I have so far: <nav class="sidenav col-md-1"> <ul class="menu" routerLinkActive="active"> ...

Create Joi Schema based on TypeScript types/interfaces

Searching for a way to convert Typescript types or interfaces into joi schema objects led me to various solutions that did the opposite, such as generating Typescript types/interfaces from joi schemas. I came across options like ts-interface-builder and ts ...

Invalid extra parameters in the $.ajax function

I am attempting to access a web service in order to retrieve some data. I must include this URL using the GET method: http://localhost/ecosat/ws/api.php?t=vw_motorista However, when I check in Chrome Developer Tools, the link is shown as: http://localho ...

jQuery UI Autocomplete for web addresses

I am trying to implement instant search with jQuery UI autocomplete, and I want to be able to add a link that will be triggered when a result is clicked. Javascript $("#searchinput").autocomplete({ source: "search/get_searchdata", select:function ...

Looking for a specific string within all attributes of an object using Angular 2

How can I search for a specific string in all properties of an object using Angular 2 with TypeScript? I have a table displaying an array of customers and I want to implement a search feature where the user can input a value and find a customer that match ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...