C# 使用Typescript和Angular从对象中删除属性

C# 使用Typescript和Angular从对象中删除属性,c#,json,angular,typescript,object-properties,C#,Json,Angular,Typescript,Object Properties,我有一个叫做RandomValue的类和一个叫做WeatherForecast的类。WeatherForecast类工作正常,数据填充到表中。RandomValues类/接口似乎返回一个没有属性的对象列表。所以我得到了一个行数正确但没有属性的表。我真的需要一些帮助 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Jso

我有一个叫做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; }
    }
}

以下是它们各自的控制器:

 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;
        }
    }
公共类随机值控制器:控制器库
{
公共随机值控制器(ILogger记录器)
{
记录器=记录器;
}
公共ILogger记录器{get;}
[HttpGet]
公共IEnumerable Get()
{
使用var httpClient=new WebClient();
Int32 NumberRows=new Random().Next(1,10);
列表值=新列表();
对于(Int32行=0;行
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.Extensions.Logging;
命名空间WebApplication14.控制器
{
[授权]
[ApiController]
[路线(“[控制器]”)]
公共类WeatherForecastController:ControllerBase
{
私有静态只读字符串[]摘要=新[]
{
“冻结”、“支撑”、“寒冷”、“凉爽”、“温和”、“温暖”、“温和”、“炎热”、“闷热”、“灼热”
};
专用只读ILogger\u记录器;
公共天气预报控制器(ILogger记录器)
{
_记录器=记录器;
}
[HttpGet]
公共IEnumerable Get()
{
var rng=新随机数();
变量示例=可枚举。范围(1,5)。选择(
指数=>新天气预报
{
日期=DateTime.Now.AddDays(索引),
温度c=下一个温度(-20,55),
摘要=摘要[rng.Next(摘要长度)]
})
.ToArray();
返回示例;
}
}
}
这两个控制器都返回所讨论类型的数组,并且模型和控制器似乎工作正常

这是我的打字脚本文件

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;
}
从'@angular/core'导入{Component,Inject};
从'@angular/common/http'导入{HttpClient};
@组成部分({
选择器:“应用程序获取数据”,
templateUrl:“./fetch data.component.html”
})
导出类FetchDataComponent{
公众预报:天气预报[];
公共随机值:随机值[];
构造函数(http:HttpClient,@Inject('BASE_URL')baseUrl:string){
http.get(baseUrl+‘weatherforecast’)
.subscribe(result=>{this.predictions=result;},error=>console.error(error));
http.get(baseUrl+randomvalues)
.subscribe(result=>{this.randomvalues=result;},error=>console.error(error));
}
}
界面天气预报{
日期:字符串;
温度c:数字;
温度f:数字;
摘要:字符串;
}
界面随机值{
userId:number;
id:编号;
标题:字符串;
已完成:字符串;
}
这是我的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>
天气预报
此组件演示如何从服务器获取数据

正在加载

日期 临时雇员(C) 临时雇员(F) 总结 {{forecast.date} {{forecast.temperatureC} {{forecast.temperatureF}} {{forecast.summary} 用户ID 身份证件 标题 完整的 {{value.userId} {{value.id} {{value.title}} {{value.completed}
WeatherForecasts是一个包含正确属性的对象列表
RandomValues是一个对象列表,但对象中没有任何属性

我发现我需要将类中的变量声明为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调试器时,值的分配似乎是正确的,所以如果有人能够解释这一点,这会有所帮助

您确定可以在后端控制器中正确获取值吗?似乎JObject为空!
        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;
        }
    }