Using TypeScript and Angular to remove properties from an object

My RandomValue class and WeatherForecast class are causing me some trouble. The WeatherForecast class is functioning properly, populating the table with data as expected. However, the RandomValues class/interface appears to be returning a list of objects without any properties. This results in a table with the correct number of rows but no corresponding properties. I am in need of assistance to resolve this issue.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace WebApplication14.Models
{
    public class RandomValue
    {
        public RandomValue RandomVal(JObject obj)
        {
            RandomValue val = new RandomValue();
            val.userId = Int32.Parse(obj.GetValue("userId").ToString());
            val.id =  Int32.Parse(obj.GetValue("id").ToString());
            val.title = obj.GetValue("title").ToString();
            val.completed = obj.GetValue("completed").ToString();
            return val;
        }

        Int32 userId { get; set; }
        Int32 id { get; set; }
        String title { get; set; }
        String completed { get; set; }
    }
}

using System;

namespace WebApplication14
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string Summary { get; set; }
    }
}

Here are their respective controllers:

 public class RandomValuesController : ControllerBase
    {
        public RandomValuesController(ILogger<RandomValuesController> logger)
        {
            Logger = logger;
        }

        public ILogger<RandomValuesController> Logger { get; }

        [HttpGet]
        public IEnumerable<RandomValue> Get()
        {
            using var httpClient = new WebClient();

            Int32 NumberRows = new Random().Next(1, 10);
            List<RandomValue> Values = new List<RandomValue>();

            for (Int32 row = 0; row < NumberRows; row++)
            {
                Int32 randomRow = new Random().Next(1, 200);
                JObject randomJSON = JObject.Parse(httpClient.DownloadString("https://jsonplaceholder.typicode.com/todos/" + randomRow));

                RandomValue value = new RandomValue().RandomVal(randomJSON);
                Values.Add(value);
            }
            RandomValue[] theValues = Values.ToArray();
            return theValues;
        }
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace WebApplication14.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            var example =  Enumerable.Range(1, 5).Select(
            index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
            return example;
        }
    }
}

Both of these controllers return an array of the specified type, and the models and controllers seem to function correctly.

Now let's take a look at my TypeScript file:

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@common/http';

@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})


export class FetchDataComponent {
  public forecasts: WeatherForecast[];
  public randomvalues: RandomValue[];


  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
      http.get<WeatherForecast[]>(baseUrl + 'weatherforecast')
          .subscribe(result => { this.forecasts = result; }, error => console.error(error));

      http.get<RandomValue[]>(baseUrl + 'randomvalues')
          .subscribe(result => { this.randomvalues = result;  }, error => console.error(error));

  }
}

interface WeatherForecast {
  date: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

interface RandomValue {
    userId: number;
    id: number;
    title: string;
    completed: string;
}

And here is my HTML file:

<h1 id="tableLabel">Weather Forecast</h1>

<p>This component showcases fetching data from the server.</p>

<p *ngIf="!forecasts"><em>Loading...</em></p>

<table class='table table-striped' aria-labelledby="tableLabe" *ngIf="forecasts">
  <thead>
    <tr>
      <th>Date</th>
      <th>Temp. (C)</th>
      <th>Temp. (F)</th>
      <th>Summary</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let forecast of forecasts">
      <td>{{ forecast.date }}</td>
      <td>{{ forecast.temperatureC }}</td>
      <td>{{ forecast.temperatureF }}</td>
      <td>{{ forecast.summary }}</td>
    </tr>
  </tbody>
</table>

<table class='table table-striped' aria-labelledby="tableLabel" *ngIf="randomvalues">
  <thead>
    <tr>
      <th>UserId</th>
      <th>Id</th>
      <th>Title</th>
      <th>Completed</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let value of randomvalues">
      <td>{{ value.userId }}</td>
      <td>{{ value.id }}</td>
      <td>{{ value.title }}</td>
      <td>{{ value.completed }}</td>
    </tr>
  </tbody>
</table>

The WeatherForecasts consist of Objects with the correct properties, while the RandomValues do not contain any properties within the Objects.

Answer №1

It came to my attention that I had to make the variables in my class public

        Int32 userId { get; set; }
        Int32 id { get; set; }
        String title { get; set; }
        String completed { get; set; }

required change

        public Int32 userId { get; set; }
        public Int32 id { get; set; }
        public String title { get; set; }
        public String completed { get; set; }

the updated class structure now appears as follows

    public class RandomValue
    {
        public Int32 userId { get; set; }
        public Int32 id { get; set; }
        public String title { get; set; }
        public Boolean? completed { get; set; }
        public RandomValue() { }
        public RandomValue RandomVal(JObject obj)
        {
            RandomValue val = new RandomValue();
            val.userId = Int32.TryParse(obj.GetValue("userId").ToString(), out int userIdResult) ? userIdResult : 0;
            val.id =  Int32.TryParse(obj.GetValue("id").ToString(), out int idRes) ? idRes : 0;
            val.title = obj.TryGetValue("title", out JToken titleToken) ? titleToken.ToString() : null;
            if (obj.TryGetValue("completed", out JToken completed) && BooleanExtensions.TryParse(completed.ToString()))
            {
                val.completed = BooleanExtensions.Parse(completed.ToString());
            }
            return val;
        }
    }

I am still puzzled about why this change was necessary, as everything appeared to function correctly when using the visual studio debugger. If anyone can shed light on this, I would appreciate it.

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

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...

retrieve the JSON information from a secure website using HTTPS

Is there a way to retrieve JSON data from an external webpage and incorporate it into my Xpages? The external website uses the https protocol. I'm unable to use: var http_request = new XMLHttpRequest(); http_request.open("GET","XX"); If anyone has ...

Execute the 'loadURL' function in the electron-Angular project when the Angular Compiler has finished preparing

When working with electron-Angular tutorials, it is common to create the window and load index.html from localhost after a set timeout. You'll often come across instructions similar to this: // set timeout to render the window not until the Angular c ...

Utilize Typescript to expand the functionality of the Express Request object

Is there a way to add a custom property to the request object in Express middleware using TypeScript without resorting to bracket notation? I am struggling to find a solution that satisfies this requirement. I would ideally like to achieve something like ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

I noticed an excess of white space on the right side of my Angular website

Check out my website here. Everything seems to be functioning correctly, however, there is an issue with scrolling on mobile. It should only scroll up and down, not left and right! I have noticed a strange white space on the right side of my site when view ...

Attributes of an object are altered upon its return from a Jquery function

After examining the following code snippet: index.html var jsonOut = $.getJSON("graph.json", function (jsonIn) { console.log(jsonIn); return jsonIn; }); console.log(jsonOut); The graph.json file contains a lengthy JSON fo ...

update icon when a router link becomes active

<div class="menuItem mb-3" *ngFor="let menuItem of menuItems"> <a routerLink="{{menuItem.link}}" routerLinkActive="active"> <img src="{{menuItem.icon}}" alt="{{menuItem.name}}" /> <p class="text-center f-12">{{me ...

Updating the state on change for an array of objects: A step-by-step guide

In my current scenario, I have a state variable defined as: const [budget, setBudget] = React.useState<{ name: string; budget: number | null }[]>(); My goal is to update this state by using a TextField based on the name and value of each input ...

What is the process for serializing/deserializing an ASP.NET JSON date with Jackson in Java?

Struggling with getting Jackson to handle JSON date strings from an ASP.NET service. The format of the string is as follows: /Date(1234567890123)/ An example of the server output looks like this: { "name" : "Bob Marley", "birthdate" : "/Date(123 ...

Creating an Observable Collection in Angular using AngularFire2 Firestore

I am currently using material 2 and attempting to develop data tables with pagination and sorting. In order to achieve this, I require my collections to be observable. However, I believe that I might be incorrectly populating or initializing the arrays in ...

What is the correct way to handle Vue props that include a dash in their name?

I am currently working on a project using Vue. Following the guidelines of eslint, I am restricted from naming props in camel case. If I try to do so, it triggers a warning saying Attribute ':clientId' must be hyphenated. eslint vue/attribute-hyp ...

Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication) After some investigation, I realized that the iss ...

The creation of fsm.WriteStream is invalid as it is not a recognized constructor

Can you help me with this issue? I am attempting to install @ng-idle/keepalive using the command npm install --save @ng-idle/core, but I encountered the following error: npm ERR! fsm.WriteStream is not a constructor npm ERR! Log files were not written due ...

Troubleshooting Puppeteer compatibility issues when using TypeScript and esModuleInterop

When attempting to use puppeteer with TypeScript and setting esModuleInterop=true in tsconfig.json, an error occurs stating puppeteer.launch is not a function If I try to import puppeteer using import * as puppeteer from "puppeteer" My questi ...

Saving information in JSON format into MongoDB

I'm currently working on a project to create a digital card generator app using node.js. My goal is to store the card data in JSON format within a MongoDB database. I am utilizing mongoose ODM for this task, but it seems that mongoose does not directl ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

When utilizing *ngIf in Angular 2, the issue of #elmentRef remaining undefined still persists

When using #elementReference with *ngIf in Angular 2, the element reference remains undefined even after the *ngIf expression evaluates to true. In this example, the value of the input will not be displayed. <input *ngIf="true" type="text" #myRef (inpu ...

Updating fields in a MongoDB collection with identical names

I am seeking guidance on how to update all instances of 'list_price' within a complex collection like this: "cost_price" : 79.9, "list_price" : 189.9, "sale_price" : 189.9, "integrations" : { "erp" : { "mbm" : { "cost_pri ...