基本上我拥有的是一个 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/