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

标签 javascript angular typescript undefined

基本上我拥有的是一个 Angular 网页,它通过我的 NodeJS 应用程序收到的 POST 将文件上传到服务器。

当我尝试通过 subirArchivo() 接收文件路径并通过名为 InsertaPersonas() 的函数发送它时,我的问题出现了。我尝试了几种方法,但总是导致函数被调用为未定义,甚至一次都没有进入函数。

这是我的代码:

     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

最佳答案

这看起来像是一个典型的绑定(bind)问题;

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() 一样调用,或者首先绑定(bind)实例,无论是在哪里您可以在 myInstance.subirArchivo.bind(myInstance) 中引用它,或者在构造函数中引用它:

class UploadController {

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

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

}

有关更多信息,请参阅Use of the JavaScript 'bind' method

关于javascript - 无法在 Typescript 中调用函数内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57028545/

相关文章:

javascript - 无法在 json 数组对象迭代中获得所需或类似的输出?

javascript - 限制jsgrid在空时添加新行

angular - 获取被删除元素的名称和ID

javascript - 选择 Angular 4 时默认选项为空

typescript - 自动从父类导入对象

javascript - 如何通过扭曲切换响应图像的大小

javascript - jquery dropzone 删除按钮不起作用

javascript - 表单和列表分离的组件

仅当 ng serve --prod 时出现 AngularFire 错误

javascript - 在深层 javascript 数组中设置对象的属性值