ChartJS 如何从http get请求中获取json响应

sqyvllje  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(238)

我从API获取数据并将其转换为json字符串,如下所示-

[HttpGet]
    public async Task<JProperty[]> GetSomeDataAsync()
    {
        try
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("myURI");
            HttpResponseMessage response = await client.GetAsync(client.BaseAddress);
            response.EnsureSuccessStatusCode();
            //string responseBody = await response.Content.ReadAsStringAsync();
            if (response != null)
            {
                jsonString = await response.Content.ReadAsStringAsync();
                 jsonObject = JObject.Parse(jsonString);
                //return JsonConvert.DeserializeObject(jsonString);
                //return JsonConvert.DeserializeObject<object>(jsonString);
               var x = jsonObject.Descendants().OfType<JProperty>().Where(p => p.Name == "observations")
                     .ToArray();
                return x;

            }
            else
            {
                throw new ArgumentNullException();
            }
        }
        catch (Exception ex)
        {
        }

上述代码写入控制器中,并将响应发送至Angular 组件,其中包含以下代码-

public economicData: any | null = null;
 public value: any;
 chart: any=[];

 constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) 
 {
 http.get<any>(baseUrl + 'somedata', { context: new 
 HttpContext().set(IsCacheable, true) 
 }).subscribe(result => { 
 this.economicData = result;
 console.log(this.economicData);
 this.value = this.economicData.observations.map((observations: 
 any) => { 
 observations.value });
 console.log(this.value);

 }, error => console.error(error));
 }`

我可以在控制器的调试模式下看到数组中的数据。但是我在控制台日志中的对象数组中没有得到任何数据,在调试时也没有在组件的结果中得到任何数据。因此,我无法将json中的属性Map到图表。
以下是console.log-enter image description here中记录的输出图像

avkwfej4

avkwfej41#

我不确定我是否完全理解你的问题,但我会给予。
此代码来自您的段段:

this.economicData = result;
console.log(this.economicData);
this.value = this.economicData.observations // other code here

根据您的控制台日志截图,this.economicData是一个数组。但是,当您尝试访问它的属性时,我希望会给予错误。

o2g1uqev

o2g1uqev2#

看看我的例子。你必须安装newtonsoft nuget包,以便这个代码的工作。

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("API URL");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var inputs = new Parameters() { inputs }; // parameters is a class of your api input parameters
    HttpResponseMessage response = await client.PostAsJsonAsync("Continuation of your API URL", inputs);

    var resultString = await response.Content.ReadAsStringAsync();

    Excel resultJson = JsonConvert.DeserializeObject<your API Output Class>(resultString)!;

    if (response.IsSuccessStatusCode)
    {
        // your code after api response receive.
    }
    else
    {
        Console.WriteLine("Error");
    }
}

如果这对某人有帮助,请投赞成票并接受这个答案。谢谢

相关问题