簡體   English   中英

無法在Typescript中的函數內調用函數

[英]Can't call a function inside a function in Typescript

基本上,我擁有的是一個Angular網頁,它通過NodeJS應用程序接收到的POST將文件上傳到服務器。

當我嘗試通過subirArchivo()接收文件路徑並通過名為InsertaPersonas()的函數發送文件路徑時,我的問題就來了。 我嘗試了幾種方法,但是它總是導致該函數被調用為undefined,甚至沒有一次輸入該函數。

這是我的代碼:

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


這是我的整個課堂: https : //pastebin.com/b8a2E3EZ

它看起來像一個典型的綁定問題。

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

您可以嘗試從調用subirArchivo函數的位置查找,並確保像myInstance.subirArchivo()那樣調用它,或者首先綁定實例,無論是在引用實例myInstance.subirArchivo.bind(myInstance)還是在構造函數中:

class UploadController {

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

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

}

有關更多信息,請參見使用JavaScript'bind'方法

您的問題可能是self參考。 由於箭頭功能,也不需要該self=this

誰在叫subirArchivo

我猜想那個范圍內的self不是您的uploadController類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM