What is the best way to map JSON object properties to specific values in Typescript?

Currently, I am working with angular 2.0 and I have a json object that is returned by a method in the following way.

this.propertiesService.addSeriesToChart(this.testId).subscribe(result => {
        this.result = result;
        });

The addSeriesToChart() method is located in a service which returns a json object.

Within the returned result, I need to assign default values to some of the null values. My attempt looks like this:

if (this.result != undefined && this.result != null) {
  this.result.json().channel.mark = "ABC"

However, the mark parameter inside the json object does not get set to "ABC", it remains null. Am I making a mistake here?

Answer №1

To start, you have the option to change an object into JSON by utilizing result.JSON() when sending the response through a service. Once you receive that JSON object, make sure to convert it with this.result=JSON.stringify(result). This method has proven effective for me.

Answer №2

If you have a variable called data in your component class that needs to be assigned the data from a JSON source, you can use an output property to emit the received data.

You can achieve this by following these steps:

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'user',
  template: '<div>Hi</div>'
})

export class AppComponent{
    data: Data;
    @Output() dataOutput: EventEmitter<Data> = new EventEmitter<Data>();

    this.propertiesService.addSeriesToChart(this.testId).subscribe(result => {
        this.data = result.json();
        this.dataOutput.emit(this.data);
    });
}

The model Data should contain the variables that will map to the JSON data:

export class Data{
   id: number;
   name: string;
}

To use the AppComponent in other parts of your app, you need to bind the event like this:

<user (dataOutput)="receiveData($event)"></user>

 export class PageComponent {
     dataReceived: Data;
     
     constructor(){}
     
     receiveData(data){
         this.dataReceived = data;
     }

     getUIData(value: any) {
          for (var name in value.selected) { 
             if (this.dataReceived != undefined && this.dataReceived != null) { 
                 if (name == 'mark') 
                     // Do something with the data 
             } 
         }
      }
 }

This approach simplifies handling JSON data in your Angular application. Give it a try and see if it fits your requirements.

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

The Redux Toolkit Slice is encountering an issue where it generates the incorrect type of "WritableDraft<AppApiError> when the extraReducer is

I defined my initial state as MednannyAppointments[] for data and AppApiError for error. However, when I hover over state.error or state.data in my extraReducer calls, the type is always WritableDraft. This behaviour is confusing to me. Even though I have ...

Creating an object type that includes boolean values, ensuring that at least one of them is true

To ensure both AgeDivisions and EventStyles have at least one true value, I need to create a unique type for each. These are the types: type AgeDivisions = { youth: boolean; middleSchool: boolean; highSchool: boolean; college: boolean; open: bo ...

Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit. However, I encountered an issue where the custom validator was not r ...

It's possible that the "device.interfaces" variable has not been defined

I am currently working on creating a USB driver in TypeScript using the libusb library to adjust my keyboard lighting. However, I encountered an issue where I received a 'possibly undefined' error when trying to retrieve the interface number. The ...

Executing the routing component prior to any other tasks

Having an issue where the ProductsService is fetching data from the server and storing it in an Array. The ProductsComponent serves as the parent component, while the ProductsListComponent and ProductListItemsComponent are its children components. The flow ...

Utilizing TypeScript's dynamic class method parameters

I've been working on integrating EventBus with TypeScript and I'm trying to create a dynamic parameter event in the emit method. How can I achieve this? interface IEventBusListener { (...params: any[]): void } class EventBus { constructo ...

"Utilizing Angular's dynamic variable feature to apply ngClass dynamically

Looking for guidance on Angular - color change on button click. The loop binding is functioning well with dynamic variable display in an outer element like {{'profile3.q2_' + (i+1) | translate}}, but facing issues with [ngClass] variable binding ...

What is the reason behind hidden DOM elements appearing when I refresh the page?

When I refresh my webpage, I notice that the DOM elements I have hidden using ngIf are briefly visible before the actual state of my webpage loads. Why might this be happening? I am currently using Angular 8 version. <div *ngIf="!callInProgress ...

Utilize regular expressions to substitute a specific string of text with an HTML tag

My task is to transform this text: let text = "#Jim, Start editing to see some magic happen!"; into this format: text = "<span style="color:red">#Jim</span>, Start editing to see some magic happen!"; Here is my ...

The functionality of the Vert.x event bus client is limited in Angular 7 when not used within a constructor

I have been attempting to integrate the vertx-eventbus-client.js 3.8.3 into my Angular web project with some success. Initially, the following code worked perfectly: declare const EventBus: any; @Injectable({ providedIn: 'root' }) export cl ...

Renew subscription following interruption

I need to trigger the updatePosition function when the mouseMove event occurs on the document, but not when it is emitted from the testEl.current element: const cursor$ = fromEvent<MouseEvent>(document, 'cursor') const scroll$ = fromEvent(d ...

Looking for help with setting up Nodemailer and installing it via NPM

I am currently developing a mobile application using Ionic with Angular/Typescript, and I'm in need of a front-end solution to dynamically send emails in the background to a specific email address. I tried using emailjs, but it requires JavaScript whi ...

Heres how you can define an index variable within a Primeng p-table similar to using ngFor

Seeking assistance to initialize an index variable like *ngFor="let d of sI.detail; let i = index" within my p-table <ng-template pTemplate="body" let-rowData > <tr class="text-center info"> <td&g ...

What is the best way to incorporate auto-completion into a browser-based editor using Monaco?

Recently, I embarked on a project to develop a browser-based editor using monaco and antlr for a unique programming language. Following an excellent guide, I found at , gave me a great start. While Monaco provides basic suggestions with ctrl + space, I am ...

The error at core.js:4002 is a NullInjectorError with a StaticInjectorError in AppModule when trying to inject FilterService into Table

While exploring PrimeNg Table control in my application - as a beginner in PrimeNg & Angular, I encountered an error No provider for FilterService! shown below: core.js:4002 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppMo ...

Is there a way to receive a comprehensive report in case the deletion process encounters an error?

Currently, I am performing a delete operation with a filter based on 2 fields: const query = await Flow.deleteOne({ _id: flowId, permissions: currentUser!.id, }); After executing the delete operation, I inspect the query object to determine its su ...

When I tap on a text element, place the cursor in the input field

I want to set the focus to an input field when I click on a specific piece of text within the same page. What is the most efficient way to achieve this? I already have a function attached to the text element. Below is the code snippet that I am working wit ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

Unable to change the directory for angular2/core - having issues with updating

Whenever I include the following code in my app.component.ts: import {Component} from 'angular2/core'; My application runs successfully, but the compiler throws an error saying Error:(1, 25) TS2307: Cannot find module 'angular2/core', ...

Having an issue with the `map` operator in Angular 8 due to using RxJS version 6.4

After updating my app to Angular 8 and installing the new version of rxjs ~6.4.0, I encountered an issue with my .map function. The error message in VC reads: "Property 'map' does not exist on type 'Observable'." I've attempted to ...