Retrieve data from a MessageEvent's properties

I have developed an Angular 6 frontend application that uses Websockets to communicate with the backend server.

Upon sending a login request, the backend responds with a JSON object:

{"type":"LoggedIn","value":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a293e2938cc6c7">[email protected]</a>","id":9,"name":"1"}}

My challenge now is to extract and display specific fields from this JSON object.

Currently, I am able to see the entire backend message using the following function:

  this.socketService.receiveEvents('LoggedIn').subscribe((message: MessageEvent) => {
      console.log('message: ' + message.data);
    });

The method "receiveEvents" aims for completeness:

 /**
   * TODO: Implement a parameter that filters relevant events for the calling functions
   * @returns {Observable<Object>}
   */
  receiveEvents(relevantEvent): Observable<Object> {
    return this._subject.asObservable().pipe(filter((event: Event) => event != null));
  }

How can I retrieve only certain fields like "type" or "value" from the JSON object?

I attempted iterating over it with a for loop, but encountered difficulties retrieving individual letters.

Any suggestions would be greatly appreciated. Thank you.

Answer №1

try something like this:

interface ServerResponse {

  messageType: string;
  dataValues: string[];
}

this.listener.receiveUpdates('UserLoggedIn').subscribe((msg: MessageEvent) => {
  const responseObj: ServerResponse = JSON.parse(msg.data);
  console.log(responseObj.messageType);
});

Following these steps should help guide you in the right direction =)

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

Refining Angular service coding techniques

In my application, I have implemented this specific format to interact with an API and retrieve data from it. Below is the code snippet taken from one of the service.ts files: getCheckoutDetails(): Observable<UserDetail> { let query = `7668`; ...

The power of Storybook and NX combined: One central Storybook instance to rule them all projects

I am managing a collection of 7 angular apps within an nx monorepo, each utilizing visual components stored in a shared-ui lib. My goal is to set up a new project with Storybook where I can automatically generate stories for all these visual components. Th ...

Angular2 and the Use of Environment Variables

I am working on an angular 2/4 app with a node server.js to serve it. I need to access an environment variable for switching between backend endpoints (using localhost for dev and another endpoint for prod). Both the frontend and backend apps are destined ...

Clicking on a component in Nuxt will trigger it to open

Is there a way to trigger a modal window to open when a button is clicked without storing the modal window in the header? file header: <template> <section class="header"> <div class="header-container"> ...

Leverage jsencrypt in Ionic 3

Struggling to hash passwords for login on my Ionic 3 app, I attempted using jsencrypt following a tutorial but encountered issues as I couldn't grasp how it works... Here's what I tried : npm install --save jsencrypt import { Component } from ...

Tips for creating a person card like the one seen in MS Teams' WhoBot

Is there a way to create a person card with status and icons that resembles the fluent UI react persona component in MS adaptive cards for a bot framework project? I am looking to achieve something like the whobot person card shown below, including all att ...

Is it possible for socket.io and node to communicate across different domains?

Is it feasible to monitor a file using watchFile that is located outside of your own domain (cross-domain)? For instance, like in the following scenario: var app = require('http').createServer(handler), io = require('socket.io').li ...

The Ionic 2 application encountering issues with building after the installation of the Facebook login plugin

Currently, I am in the process of developing a Hybrid app using Ionic-2 on Ubuntu. I encountered an issue when trying to add Facebook login functionality to my app. After installing the Facebook plugin, the app build fails. However, if I remove the Faceb ...

When uploading from Angular 2, PHP fails to populate the $_POST and $_FILES variables

I'm encountering difficulties when trying to upload files and data to my server using Angular 2 and PHP. After following the instructions in File Upload In Angular 2? to upload data and files from Angular 2, everything appears to be functioning corre ...

Error encountered: "The requested resource does not have the 'Access-Control-Allow-Origin' header in Angular 6 and Nodejs."

I have encountered an issue with my Angular 6 app and Node.js. When I submit the form, I am receiving the following error: Failed to load http://localhost:3000/contact/send: Response to preflight request doesn't pass access control check: No 'Ac ...

What is the reason for the inability to import a router for express in TypeScript?

I have been working on setting up a basic Hello World REST service using NodeJS and Typescript. I attempted to organize the routers into separate files, but encountered some issues along the way. Specifically, when making a GET call to http://localhost:30 ...

What is the best way to run a scheduled task automatically using node-cron?

I have a custom function that saves data to the database using the POST method. When testing it with Postman, I send an empty POST request to trigger the controller. Upon execution, the function triggers two more functions. One of them is responsible for ...

Steps for setting up an auth guard:1. Define a

I am facing an issue with implementing two guards in my Angular application. The first guard is supposed to restrict unauthorized users from accessing certain pages, while the second guard is meant to prevent authorized users from accessing the "sign-in" a ...

Encountering a JS_Parse_Error error while trying to update the TypeScript target to ES6 using aurelia-b

I encountered an issue that is causing difficulties in utilizing async/await or yield/generators. Initially, I utilized the aurelia skeleton for typescript & asp5 (aspnetcore) with the default target set to es5. To incorporate async/await in my TypeScript ...

Attempting to determine the size of a property within a nested object that exists within an array of objects

I am currently working on implementing a scoring system for two teams. The scoring data is stored in an array that identifies the team (home or away) that scored the goal. My goal is to calculate the total number of goals scored by either team with an ID o ...

Unusual function call patterns observed in generic classes

After compiling the code below, it runs without any issues interface A { x: string; } interface B { x: string; } type C<D extends A> = D | B; declare function funcA<D extends A, E extends C<D> = C<D>>(): E | E[] | undefined; d ...

Constructor polymorphism in TypeScript allows for the creation of multiple constructor signatures

Consider this straightforward hierarchy of classes : class Vehicle {} class Car extends Vehicle { wheels: Number constructor(wheels: Number) { super() this.wheels = wheels } } I am looking to store a constructor type that ext ...

What causes the package-lock.json to contain newer versions of packages compared to package.json following a new npm installation in Angular?

Back in the year 2017 or around that time, npm reportedly made a decision to automatically update packages in package-lock.json if the versions listed in package.json were higher. An interesting issue I've noticed is that my project seems to be upgra ...

Guide on setting and retrieving values with a service using a map function

I have a shared HTML <inventory-products-list *ngIf="toggle" [products]="products" (qrCode)="generateQRCode($event)" (undeleted)="undelete($event)" (deleted)="deleteProduct($event)"></inventory-products-list> this I need to use in different ...

A secure way to perform a deep update on any type, even if it is completely different from the original

Is there a method to eliminate the as any in the update_substate function? It seems type-safe when directly invoking the update_state function, so it should also be safe when invoked indirectly, right? These functions are meant to be lightweight helpers ...