[英]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.