简体   繁体   中英

Properties getting dropped from Object using Typescript and Angular

I have a class called RandomValue and a class called WeatherForecast. The WeatherForecast class works correctly and data populates the table. The RandomValues class/interface seems to return a list of objects with no properties. So I get a table with the correct number of rows but no properties. I could really use some help with this

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 the controllers return an array of the type in question and the models and controllers seem to work fine.

Now here is my typescript file

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/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 demonstrates fetching data from the server.</p>

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

<table class='table table-striped' aria-labelledby="tableLabel" *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>

WeatherForecasts is a list of Objects with the correct properties inside them RandomValues is a list of Objects but the Objects don't have any properties inside them

I found out that I needed to declare the variables in my class as public

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

needed to be

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

the class now looks like

    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 not sure why I needed to do this because it certainly seemed like the values were being assigned correctly when using the visual studio debugger so if anyone can explain it that would help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM