bojackhorseman99
bojackhorseman99

Reputation: 329

Can't call a function inside a function in Typescript

basically what i have is an Angular Web Page that uploads a file to the server through a POST which my NodeJS app receives.

My problem comes when i am trying to receive the file path through subirArchivo() and sending it through a function called InsertaPersonas(). I have tried several methods but it always results in the function being called undefined, it doesn't even enter the function once.

Here is my code:

     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();
    });
  }


Here it is my whole class: https://pastebin.com/b8a2E3EZ

Upvotes: 0

Views: 3346

Answers (2)

Leonard Pauli
Leonard Pauli

Reputation: 2693

It looks like a typical 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 could try finding from where you call your subirArchivo function, and make sure it is called like myInstance.subirArchivo(), or bind the instance first, either where you reference it myInstance.subirArchivo.bind(myInstance), or in the constructor:

class UploadController {

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

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

}

For more, see Use of the JavaScript 'bind' method

Upvotes: 2

Ion
Ion

Reputation: 1292

Your problem is probably the self reference. That self=this is also unneeded because of the arrow function.

Who is calling subirArchivo?

I would guess that self in that scope is not your uploadController class.

Upvotes: 1

Related Questions