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

If the text width of a label exceeds the total width of its container, intelligently display a sub-string based on pixel calculations

I am looking to shorten the text inside a label if its width exceeds the total width of its container. Instead of displaying the full text, I want to display a sub-string of it. if (SensorType.Text.Length >= 25) { SensorType.Text = SensorType.Text ...

What kind of Antd type should be used for the form's onFinish event?

Currently, I find myself including the following code snippet repeatedly throughout my project: // eslint-disable-next-line @typescript-eslint/no-explicit-any const handleCreate = (input: any): void => { saveToBackend({ title: input.title, oth ...

Access form variables through a C# web service using PHP's cURL functionality

Hi there, I am faced with the challenge of reading form elements sent from a curl library on another server using C#. Being primarily a PHP developer, I am unsure of how to access these variables in C#. If I were coding this in PHP, my code would look some ...

Error in Angular 7: Image is not being rendered

Currently, I am working on a project that involves Angular JS. I have been following this example: https://jsbin.com/gumaraz/edit?html,output However, I need to transition this code to Angular 7. I have tried upgrading the code from Angular.js to Angular ...

Extracting information from JSON ( AngularJS)

I have a collection of questions stored in my JSON file, but I want to display only one at a time until the user selects the correct answer and proceeds to the next question. Here is the HTML template: <div ng-controller="quizController"> <ul> ...

Utilize LINQ to populate a class instance with an enum types

In my program, I have a generic List<Person> PersonList which contains entries for different persons. class Person { public string name {get ; set;} public string lastName {get ; set;} public decimal income {get ; set;} } I have a ...

Hiding a div in Angular when selecting a language using ngx translate from a different component

I am currently working on an Angular application with version 16. I have integrated ngx translate for multiple languages support. Here is what I am trying to achieve: Within my header-component, there is a dropdown menu to switch between English and Spani ...

sed is not able to pick out the values

Looking for assistance with the sed command. I am trying to extract JSON values and assign them to variables using sed. Can someone provide guidance on how this can be achieved? For example: echo "{url:news.google.com,int:3}" | sed ? url=news.google.com ...

Preventing over-purchasing products by managing Knex.js inventory levels

Currently, I am in the process of developing an online store for my school's guild organization. I must admit that I lack experience working with databases and Knex.js is still a bit challenging for me. An issue arises when multiple users simultaneo ...

Transferring information from childA component through its parent component and into childB component

In my project, there is a main parent component with two child components: 1. app-search-list and 2. app-vertical-menu The data is passed from the app-search-list (childA) component to its parent component, and then from the parent to the app-vertical-men ...

What is the best way to update the value of a variable within a specific child component that is displayed using ngFor?

Hello there, I'm in need of some assistance with a coding issue. I have a parent component named "users-list" that displays a list of child components called "user" using *ngFor. Each component's class is dynamic and depends on various internal v ...

Error message in TypeScript: A dynamic property name must be a valid type such as 'string', 'number', 'symbol', or 'any'

Attempting to utilize the computer property name feature in my TypeScript code: import {camelCase} from "lodash"; const camelizeKeys = (obj:any):any => { if (Array.isArray(obj)) { return obj.map(v => camelizeKeys(v)); } else if (ob ...

Autodesk Forge serves as a hub for hosting dependencies on a nearby server

Our company has implemented an Angular/TypeScript version of the Forge Viewer, currently loading dependencies from Autodesk's server. To ensure these files are always accessible to our customers, we want to host them on our own servers. However, attem ...

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

Unable to fetch options for drop-down list from Database

As someone who is new to frontend application development, I am facing a challenge in populating a Select list from the database. Despite following similar approaches like the one discussed in How to populate select dropdown elements with data from API - R ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...

The error of "No 'Access-Control-Allow-Origin' header is present on the requested resource" persists even after implementing the Access-Control-Allow-Origin header

I'm trying to retrieve JSON data from a Firebase cloud function. The JSON URL works fine on the browser and my Android app, but I encounter issues when trying to fetch it in my JavaScript code. This results in an error message: No 'Access-Cont ...

Utilizing Nested JSON in Excel via Web API Integration

My current task involves extracting web analytics data from a nested JSON structure using Excel's Power Query feature to gather internet data. The schema is structured as follows: // Information within "~/sites" { "id": 1852274, "url": "http://li ...

Leveraging the power of SQL Server Indexed View in tandem with the functionality of OPEN

My database table consists of a single row and column storing a JSON array with about 30MB/16k objects: CREATE TABLE [dbo].[CitiesTable] ( [CitiesJson] [NVARCHAR](MAX) NOT NULL ) ON [PRIMARY] GO INSERT INTO [dbo].[CitiesTable] ([CitiesJson]) VALUES ...

My goal is to prevent the need for redirection (301) while using Scrapy and generate a JSON file instead

Task at Hand I am interested in web scraping using Scrapy to create a JSON file. Currently, I am enrolled in a course on "Data Visualization with Python and JavaScript". However, my attempts to create a JSON file have been unsuccessful. I suspect the issu ...