Converting JSON data into a class with calculated attributes using Angular 2

I've been working on converting a JSON object into a TypeScript class with computed properties. My issue is that when I do the mapping, it correctly captures all the returned values but ignores the computed properties, even if they have default values.

My goal is for the ShowPanel property to default to true.

export class Maintenance {
  Id?: number;
  Name?: string;

  // This computed property should be included in the object
  ShowPanel: boolean = true;
}

@Component({
  moduleId: module.id,
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent {
   ngOnInit(){
      this.http.get('lookup/getstatusinformation')
               .map(res => <Maintenance[]>res.json())
               .subscribe(res => this.listMaintenance = res);
   }
}

Answer №1

After the JSON is deserialized, any properties that are missing in the data will be assigned the default value on the target object, making it seem like those values were originally part of the response.

In my own approach, I go through each object created and reset any computed values as needed.

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 Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...

What is the best way to solve the Hackerrank Binary Tree problem using TypeScript and output the

Here is the coding challenge from Hackerrank: Given a pointer to the root of a binary tree, you are required to display the level order traversal of the tree. In level-order traversal, nodes are visited level by level from left to right. Implement the fun ...

When the modifications are successfully saved in the database, Ajax will display an error status of 200 along with an OK

I have created a webservice that allows users to modify food details in my database. After processing the request and making changes, I encountered an error. How can I resolve this issue? //MODIFYING FOOD $("button#editFood" ...

What is the best way to eliminate the occurrence of the word 'undefined' from the cycle output?

Can anyone assist with solving this issue? The webpage on JSFIDDLE displays 4 news containers, but an 'undefined' string appears before the first news container. I am looking to remove that 'undefined' string. Here is the HTML code: ...

The 'Subscription' type does not contain the properties: source, operator, lift, subscribe, and three other properties that are present in the 'Observable<EnumValue[]>' type

Are you struggling with assigning an Observable<EnumValue[]> to another Observable<EnumValue[]>? fetchContactLocationStates() { this.contactLocationStates$ = this.enumValues$ .pipe(takeUntil(this.destroy$)) .subscribe(x => x.fil ...

Equivalent JSON.NET settings for default dates in JavaScriptSerializer

When using the JQuery Ganntt plugin, dates need to be formatted in the Unix epoch format. To achieve this, I am utilizing Newtonsoft's Json.Net with specific settings. JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings { ...

Encountering the error "ValueError: No Json object could be decoded" while executing a Python MapReduce script using Hadoop Streaming

I'm in the process of running a basic Python mapreduce script on Hadoop using streaming. The mapper section is responsible for loading a JSON document, extracting text from a property, and outputting each word with a count of 1, which will later be co ...

Ways to navigate to a routerlink in Angular 2 without passing any parameters

Struggling with accessing a routerlink in Angular 2 without its parameters. The goal is to use the routerlinks to determine whether or not to display a specific element in the navigation. For normal routerlinks without parameters, I do it like this: *ngIf ...

Is it possible in Angular to generate a module and component without including a CSS file in a single command?

Is it possible to generate a Module linked to a component without automatically creating a css file? For example, the default method I've been using involves: ng generate module name / ng generate component name This results in the typical componen ...

Is there a way to update a BehaviorSubject value without using the next method?

I am looking for a solution to update the value of my BehaviorSubject without causing any subscriptions to be triggered. I attempted the following: this.mySubject = new BehaviorSubject(newVal); Unfortunately, this approach also removes all existing subs ...

Converting Json string containing escape characters into a valid json format on Android

Trying to parse a JSON response from a REST call has been difficult due to the presence of escape characters such as "\n". Even replacing "\" with "" did not yield the desired results. "[{\"message_id\":50870,\"message\":&bso ...

Exploring ModuleFederation with Ionic and Angular showcasing the "unique" NG_VALUE_ACCESSOR concept

I am currently working in an NX workspace with the latest versions of NX, Angular, and Ionic. Within my workspace, I have one host app and one remote. My current challenge involves creating a page with two form controls. Whenever I attempt to create a bin ...

The observable did not trigger the next() callback

I'm currently working on incorporating a global loading indicator that can be utilized throughout the entire application. I have created an injectable service with show and hide functions: import { Injectable } from '@angular/core'; import ...

The error message "TypeError: (0 , N.createContext) is not a function" indicates that

I'm currently in the process of developing a cutting-edge application using Next.js 14, TypeScript, and Telegram Open Network. However, I've hit a roadblock while attempting to incorporate the TONConnectUIProvider at the root of my app. Upon run ...

Unable to locate the module from my personal library in Typescript

The Query Why is my ng2-orm package not importing or being recognized by vscode when I try to import Config from 'ng2-orm'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser&a ...

"Encountered an ENOENT error message following the deployment

I'm really hoping for some insight into the current situation. Deploying an Angular 7 / .Net Core 2 application to Azure is giving me trouble. I am utilizing the publish profile provided by Azure in Visual Studio. Everything runs smoothly when testi ...

Versions of Angular that are compatible with Ionic 2 (do not have an exported member)

How do I determine the compatible Angular version for each Ionic version? I keep encountering errors like "has no exported member." For example: The module ".../node_modules/@angular/core/index" does not have an exported member called InjectionToken. The ...

Your global Angular CLI version (6.1.2) surpasses that of your local version (1.5.0). Which version of Angular CLI should be used locally?

I am experiencing an error where my global Angular CLI version (6.1.2) is higher than my local version (1.5.0). Can someone provide assistance with this issue? Below are the details of my local versions: Angular CLI: 1.5.0 Node: 8.11.3 OS: win32 ia32 Ang ...

Managing Geolocation in Ionic2 presenting challenges

Attempting to utilize Geolocation in ionic2 for device location access. Referred to the official documentation on https://ionicframework.com/docs/native/geolocation/. Successfully installed the necessary packages: $ ionic plugin add cordova-plugin-geoloca ...

Transforming a JSON or dictionary into a structured dataframe

I recently received the output from an API service as shown below: {'node': [{u'A': 300, 'B': u'Ken', u'C': 101901}, {u'A': 400, u'B': u'Miki', u'C': 500001}]} Do y ...