简体   繁体   English

在Socket.IO上发射Typescript数据对象

[英]Emitting Typescript Data Objects on Socket.IO

I have defined a simple User class in Typescript as follows 我在Typescript中定义了一个简单的User类,如下所示

export class User {
    constructor(public id: string);
}

from my socket.io server I emit a message with an instantiated version of this User class, eg, 从我的socket.io服务器发出一个带有该User类的实例化版本的消息,例如,

var user = new User('billy');
io.emit('MyMessage', user);

on my client I listen for my message as follows 在我的客户上,我听我的消息如下

io.on('MyMessage', (user: User) => {    
    console.log(user); // This prints '[object]'
    console.log(user.id); // This prints 'undefined'
    console.log(user[0].id); // This prints 'billy'
}

Data between sockets therefore appears to be sent as an array of objects, the typescript definition for the emit method also shows this, ie, 因此,套接字之间的数据似乎是作为对象数组发送的, emit方法的打字稿定义也显示了这一点,即

emit( event: string, ...args: any[]): Namespace;

Thus, is the cleanest way for me to use the sent data to use array addressing as shown in the third console log line above, ie, user[0].id , or is there a cleaner way to do this? 因此,对于我来说,使用发送的数据来使用数组寻址的最干净方法是上面第三条控制台日志行所示,即user[0].id ,还是有一种更干净的方法呢?

seems like you can do 好像你可以做

io.emit('MyMessage', user, someData, someAnotherData);

And when you catch it you get 当你抓住它,你会得到

io.on('MyMessage', data => {    
    data[0] // user
    data[1] // someData
    data[2] // someAnotherData
});

You can use destructuring to manage it 您可以使用分解来管理它

io.on('MyMessage', ([user]: [User]) => {    
    console.log(user.id);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM