0

我有一个名为 RandomValue 的类和一个名为 WeatherForecast 的类。WeatherForecast 类工作正常并且数据填充表。RandomValues 类/接口似乎返回一个没有属性的对象列表。所以我得到了一个行数正确但没有属性的表。我真的可以在这方面使用一些帮助

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; }
    }
}

这是他们各自的控制器:

 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;
        }
    }
}

两个控制器都返回一个相关类型的数组,模型和控制器似乎工作正常。

现在这是我的打字稿文件

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;
}

这是我的html文件

<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 是其中包含正确属性的对象列表 RandomValues 是对象列表,但对象内部没有任何属性

4

1 回答 1

0

我发现我需要将我的类中的变量声明为 public

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

需要是

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

现在的课程看起来像

    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;
        }
    }

我仍然不确定为什么我需要这样做,因为在使用 Visual Studio 调试器时,似乎确实正确分配了值,所以如果有人能解释它会有所帮助

于 2019-12-04T20:31:36.433 回答