The issue with converting a string into an object in Typescript

I am having trouble converting the JSON response from the websocket server to a TypeScript object. I've been trying to debug it but can't seem to find where the error lies. Can anyone assist me in resolving this issue?

Below is the code snippet for the websocket server:

const wsServer: Server = new Server({port: WEBSOCKET_PORT});

console.log('WebSocket server is listening on port 8085');
export class PushData {
  constructor(public push: string,
              public workflowId: number) {
  }
}

wsServer.on('connection', (websocket, req) => {
  websocket.send('This message was pushed by WebSocket server');
  websocket.send('Data pushed by server: ');
  websocket.on('message', (message) => {
    console.log('Server received : %s', message);
    const todaysDate = new Date();
    // websocket.send('Data pushed by server: ' + todaysDate.toString());
    const request1 = new PushData('data', 30);
    websocket.send(JSON.stringify(request1));
   }
}

Now, moving on to the client Class service:

private faceSubject = new BehaviorSubject<any>(null);
createObservableSocket(url: string): Observable<string> {
  this.ws = new WebSocket(url);
  return new Observable(
    observer => {
      this.ws.onmessage = (event) => observer.next(event.data);
      this.ws.onerror = (event) => observer.error(event);
      this.ws.onclose = (event) => observer.complete();
    }
  );
}

And finally, here is the client component where I'm attempting to perform the conversion:

ngAfterViewInit(): void {
  this.drawOverlayPicture();

  // subscribe to the subject
  this.subscription = this.wsService.getFaceSubject()
    .subscribe((data: PushData) => {
        if (data !== null) {
          console.log('received data from server', data);
          console.log('received data from server push=', data.push);
          // var ob = JSON.parse(JSON.stringify(data));
          // console.log('received data from server, workflowId=', (<PushData> ob).push);
          console.log(this.i++);
}

In my attempts, I always end up with data.push = undefined. Any guidance on how to properly convert the websocket response to an object would be greatly appreciated. Thank you!

Answer №1

UPDATE : The server will only send a PushData object once it receives a message from the client, but it will initially send two strings to the client upon connection. This is why you are receiving an error stating data.push is undefined because the data consists of only strings.

websocket.send('This message was sent by the WebSocket server');  
websocket.send('Data sent by the server: ');

In order to receive the pushData object, the client needs to emit a message to trigger the process!

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

Exploring the methods of connecting with data-checked and data-unchecked attributes in Angular

Utilizing a toggle switch, I am able to determine what text to display in the div by utilizing html attributes such as data-checked and data-unchecked. In addition, I have an Angular pipe that translates all texts on the website based on the selected lang ...

Uploading images to an S3 bucket using Angular4 and saving the response.Location in a global variable for easy access in other functions or methods

Hello, I am currently working on uploading an image to an Amazon S3 server using Angular 4. My goal is to retrieve the response.Location, which is returned from S3 as a URL, and save it to a global variable for easy access. However, I am facing some challe ...

What is the method for identifying the corresponding value that should be linked to the remaining select based on the selected option?

Is it possible for the first select to dynamically affect the value of another select? <form [formGroup]="myForm"> <div class="modal-body"> <p><strong>Rate:</strong></p> {{ApplesPerCash}} <p><st ...

What could be causing my mdx files to not display basic markdown elements such as lists and headings? (Next.js, mdx-bundler)

Trying to implement Kent C Dodds mdx-bundler with the Next.js typescript blog starter example is proving challenging. While it successfully renders JSX and certain markdown elements, basic markdown syntax like lists and paragraph spacing seem to be malfunc ...

I encountered an issue when attempting to display a validation message on an Angular form

As I work on creating an Angular form and implementing validation, I encountered an issue when attempting to display a message when a field is left empty. My approach involved using ng-for in a span tag, but unfortunately, an error occurred. Here is the H ...

Angular - Loading images on the fly

After scouring numerous resources, I couldn't find a resolution to my issue. For your information, I am utilizing ASP.net Core 2.0's default angular project In the process of developing an Angular application, I am faced with the challenge of ...

Can someone guide me on how to make a Carousel responsive using Angular?

HTML: <div class="voxel-row"> <div class="voxel-col-4"><h2 id="vagas_recentes">vagas recentes</h2></div> </div> <div id="carouselExampleControls" cl ...

What exactly does the question mark represent in the code structure as indicated in VSCode?

When looking at the image, you can see that in the description of done(), VSCode indicates the type of parameters using a colon error: any or sometimes with a question mark and colon user?: any. So, what exactly is the distinction between these two ways o ...

Showing object data in TypeScript HTML when the object property starts with a numeral

Below is the function found in the TypeScript file that retrieves data from an API: .ts file getMachineConfigsByid(id) { this.machinesService.getMachineConfigById(id).subscribe((res) => { if (res.status === 'success') { ...

How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status: export enum Status { Active = "Active", Inactive = "Inactive", } Additionally, I have a UserStatus enum: export enum UserStatus { Active = Status.Active, }; There is also a common dto that inc ...

Issue encountered when upgrading from Angular 4 to Angular 5: Module '@angular/router' is not found

I recently made the switch from angular 2 to angular 5. However, after the upgrade, I encountered some errors in my ts file. Should I remove @angular/core and @angular/router in angular 5? Here is a snippet of my package.json post-upgrade. Below are the de ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

What is the best way to integrate JSON:API with Angular and RxJs?

Currently, I have a Laravel API that adheres to the json:api spec and functions smoothly with Postman for making requests on related resources. However, I am facing challenges in understanding how to utilize this API with my Angular front-end. To kickstar ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...

When using TypeScript and React with Babel, an error may occur: "ReferenceError: The variable 'regeneratorRuntime'

I've been delving into learning typescript, react, and babel, and here is the code I've come up with: export default function App(): JSX.Element { console.log('+++++ came inside App +++++++ '); const {state, dispatch} = useCont ...

The dropdown will close automatically when the user clicks outside of it

My dropdown setup requires it to close when the user clicks outside of it. <div [class.open]="qtydropdownOpened"> <button (click)="qtydropdownOpened = !qtydropdownOpened" type="button" data-toggle="dropdown" aria-haspopup="true" [att ...

Experimenting with altering the heights of two Views using GestureHandler in React Native

I am currently working on a project where I need to implement height adjustable Views using React Native. One particular aspect has been causing me some trouble. I'm trying to create two stacked Views with a draggable line in between them so that the ...

Exploring the zorro components (nz-tree) in Angular for effective testing with Jasmine and Karma

How can I access the data in the $event and verify if the treeClick method is being called upon click? When running the test file, I encountered the following error: "Expected spy treeClick to have been called once. It was called 0 times." In t ...

retrieve data from URL parameters (navigation backward)

When navigating from the main page to the transaction page and then to the details page, I have implemented a go back feature on the details page. Using the state, I pass data when navigating back so that I can access it again from the transaction page. H ...