简体   繁体   English

无法在Typescript中的函数内调用函数

[英]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. 基本上,我拥有的是一个Angular网页,它通过NodeJS应用程序接收到的POST将文件上传到服务器。

My problem comes when i am trying to receive the file path through subirArchivo() and sending it through a function called InsertaPersonas(). 当我尝试通过subirArchivo()接收文件路径并通过名为InsertaPersonas()的函数发送文件路径时,我的问题就来了。 I have tried several methods but it always results in the function being called undefined, it doesn't even enter the function once. 我尝试了几种方法,但是它总是导致该函数被调用为undefined,甚至没有一次输入该函数。

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 这是我的整个课堂: https : //pastebin.com/b8a2E3EZ

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: 您可以尝试从调用subirArchivo函数的位置查找,并确保像myInstance.subirArchivo()那样调用它,或者首先绑定实例,无论是在引用实例myInstance.subirArchivo.bind(myInstance)还是在构造函数中:

class UploadController {

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

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

}

For more, see Use of the JavaScript 'bind' method 有关更多信息,请参见使用JavaScript'bind'方法

Your problem is probably the self reference. 您的问题可能是self参考。 That self=this is also unneeded because of the arrow function. 由于箭头功能,也不需要该self=this

Who is calling subirArchivo ? 谁在叫subirArchivo

I would guess that self in that scope is not your uploadController class. 我猜想那个范围内的self不是您的uploadController类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM