我正在尝试使用typescript创建从服务器到客户端的socket.io连接,我需要在构造函数中定义“socket”对象,以便对象可以使用套接字向客户端发送数据。但是,当编译为javascript时,套接字对象不会被定义为该类的变量,这会阻止它被调用。
这是打字稿。
导出类上传{
directory = "./data";
socket: Socket;
constructor(socket:Socket) {
this.socket = socket;
}
public upload(req:express.Request, res) {
this.socket.emit('fileReceivedConfirmation', {
successful:true,
filePath: filePath,
originalName: originalFileName
});
}
这是相应的javascript
function Upload(socket) {
this.directory = "./data";
this.socket = socket;
}
Upload.prototype.upload = function (req, res) {
this.socket.emit('fileReceivedConfirmation', {
successful: true,
filePath: filePath,
originalName: originalFileName
});
}
套接字变量未在编译的Javascript中的任何位置定义 - 当函数调用socket时会产生此错误。
C:\Users\Me\WebstormProjects\Core\lib\Upload.js:43
this.socket.emit('fileReceivedConfirmation', {
^
TypeError: Cannot call method 'emit' of undefined
答案 0 :(得分:0)
尝试更改以下代码
io.sockets.on('connection', function (socket) {
this.socket = socket;
});
到此
io.sockets.on('connection', (socket:any):void => {
this.socket = socket;
});
答案 1 :(得分:0)
我将变量转换为静态并且有效:
directory = "./data";
static socket:Socket;
constructor(socket:Socket) {
console.log("Creating socket");
Upload.socket = socket;
}