2013-12-22 53 views
0

我試圖創建一個socket.io連接從服務器到客戶端使用typecript,爲此我需要在構造函數中定義「套接字」對象,以便對象可以發送數據到客戶使用套接字。然而,當編譯爲javascript以防止被調用時,套接字對象不會被定義爲該類的變量。在Typescript中沒有定義全局變量

這是打字稿。

出口類上傳{

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的任何地方定義 - 它創建這個錯誤,當函數調用插座。

C:\Users\Me\WebstormProjects\Core\lib\Upload.js:43 
      this.socket.emit('fileReceivedConfirmation', { 
         ^
TypeError: Cannot call method 'emit' of undefined 

回答

0

我轉換的變量靜態和它的工作:

directory = "./data"; 
static socket:Socket; 

constructor(socket:Socket) { 
    console.log("Creating socket"); 
    Upload.socket = socket; 
} 
0

嘗試下面的代碼

io.sockets.on('connection', function (socket) { 
    this.socket = socket; 
}); 

改成這樣

io.sockets.on('connection', (socket:any):void => { 
     this.socket = socket; 
    }); 
+0

對不起的問題有改變。請檢查問題。謝謝。 – EternallyCurious

+0

該錯誤表明您沒有爲'socket'參數分配任何值。你如何初始化Upload構造函數? –