Broadcasting TypeScript Data Structures via Socket.IO

In my Typescript code, I have created a basic User class as shown below:

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

When I emit a message from my socket.io server, I include an instance of the User class like this:

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

On the client side, I am listening for the same message like so:

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

It seems that the data sent between sockets is treated as an array of objects. The TypeScript definition of the emit method also supports this, as seen below:

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

Therefore, is using array addressing like user[0].id the best way to access the sent data, or is there a cleaner method available?

Answer №1

It appears that you have the ability to

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

Upon catching it, you will receive

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

Utilizing destructuring can help you handle it efficiently

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selection determines the value of two fields

This form has predefined values that are used to create a link, but the issue is that these values vary depending on the location. Can you assist me with this problem? <input type="radio" id="iconapp1" name="department" value="1250"/><label for ...

Using Button Elements to Initiate Server Requests in Node.js

I'm currently in the process of designing a menu for my Node JS application and I'm struggling to find a way to send server requests without relying on the browser's navigation bar. Here is how my directory structure is organized: /applica ...

Configuring Chart.js in Laravel to Initialize with Value of Zero

I'm struggling to set my Chart.js chart to zero in my Laravel project. Could someone please help me with this? $chartjs = app()->chartjs ->name('lineChartTest') ->type('bar') ->size(['width' => ...

Displaying a loading template within an Angular component

While reviewing some code in AngularJS version 1.2.22, I came across the following snippet in the HTML: <div class="mainContent" ng-include="content"> </div> Within its corresponding controller, I found this: $scope.content = 'templates ...

Creating a dynamic slideshow with automated arrow navigation is simpler than you may think

I have successfully tested the slideshow and it is functioning perfectly without any issues. I would like to have a dual slideshow setup (slideshow 1 and slideshow 2) with next and previous buttons, but I am interested in adding an automatic sliding featur ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

Transferring data between components in Ionic 2: Service to Page

My service code includes two functions - one for creating a native storage with IP and port, and the other for retrieving values from the native storage. DatabaseService export class DatabaseService { ... public ip: string; public port: string; . ...

Executing a search within the current connection in Node.js

In the code snippet provided, the need is to execute the second SQL query (query2) after constructing it based on the results of the first query (query1). However, even though the second query is successfully built, it is not being executed. Assistance i ...

What is the best jQuery library to add to my website?

I have included several jQuery scripts on my website for various functionalities such as sticky header, anchors, and animations. I am wondering if it is necessary to include all of them or if I can just include one or two? Here are the jQuery scripts I ha ...

"Encountered an error: AngularJS is unable to read the property 'push' as it is

I'm attempting to generate an array using data retrieved from an API. However, I continue to encounter an error message stating cannot read property 'push' of undefined in Javascript. Could someone please guide me on how to resolve this iss ...

css based on the current time in the United States

I have a working code that currently reads the user's computer time, but I specifically need to get the hours from the USA regardless of the user's location. The CSS should be applied based on USA time. <script type="text/javascript"> dat ...

Could you explain the distinction between Node.bind() and Template Binding?

Currently, I am exploring the documentation for Google Polymer and have come across two types of data binding - Node.bind() and Template Binding. Can someone please explain the distinction between Node.bind() and Template Binding to me? ...

Unit testing with Jest in TypeScript for mocking Express and Mongoose

I've been struggling to find comprehensive resources on using jest.fn() to mock TypeScript classes and their methods, like express' Request, Response, NextFunction, and the save() method on a mongoose model. For instance, suppose I have the foll ...

What is the formula for determining the size of an image using JavaScript, jQuery, or Java?

I'm looking to determine the dimensions of an image. I have both the image src and base64 data available. My goal is to display the current size of the image. I am working with Java and JavaScript. Is there a way for me to calculate the image size usi ...

Exploring Angular: Understanding Events and Addressing the Error Message "subscribe is not a function"

Recently, I delved into the basics of Angular 4 and encountered a roadblock while trying to listen to an emitted event. Let me share a simple example that demonstrates the issue: DateSenderComponent is sending out the current date to be handled by its par ...

Tips for maintaining the data on a page continuously updating in AngularJS

I have this code snippet: $cookieStore.put('profileData', $scope.profileData); var profileData = $cookieStore.get('profileData'); $scope.init = function(){ var profileData = $cookieStore.get('pr ...

Passing array data from JavaScript to PHP using POST method in Joomla 3.x

Looking for a way to send an array from JavaScript to a Joomla 3.x PHP file? var data = ['foo', 'bar']; $.post('index.php?option=component&view=componentview&Itemid=123&tmpl=component&layout=xlsx', {'xls ...

What could be causing my Bootstrap datepicker to malfunction?

A while ago, my Bootstrap datetimepicker component was functioning perfectly in my code. However, it has suddenly stopped working and I am seeking assistance to get it running smoothly again. Below is the HTML code snippet: <script src="https://cd ...

Is there a way to determine when an HTML video has finished playing?

I'm working on a webpage that features multiple videos. I want to capture a specific value from an input field and display it once a video finishes playing. Below is my current setup: HTML <input type='text' name='profileUsernam ...

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...