简体   繁体   中英

Emitting Typescript Data Objects on Socket.IO

I have defined a simple User class in Typescript as follows

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,

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( 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?

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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