Fetch data from asp.net into highchart.js

 ̄綄美尐妖づ 提交于 2020-08-10 20:13:29

问题


I'm trying to make an application with highchart and asp.net and I followed several tutorials and applications because it's a new thing for me. But I don't know how to fetch data from asp.net into highcharts.js. I tried to do a getChartData function following one video and then I realised that is for chart.js.Can you give me a idea? This is my code:

bar-chart.ts

import { Component, OnInit } from '@angular/core';
import * as Highcharts from 'highcharts';
import { SalesDataService } from '../../services/sales-data.service';
import * as moment from 'moment';
@Component({
  selector: 'app-bar-chart',
  templateUrl: './bar-chart.component.html',
  styleUrls: ['./bar-chart.component.css']
})
export class BarChartComponent implements OnInit {

  constructor(private _salesDataServices:SalesDataService ){}

  orders:any;
  orderLabels:string[];
  orderData:number[];
  public barChartLabels:string[];
  public barChartData:any[];

  title = 'myHighChartsApp';
  highcharts = Highcharts;
  public options: any ={
  chart : {
    type: "column"
    },
    title: {
    text: "Monthly Sales Chart Department Wise"
    },

    xAxis:{
    },
    yAxis: {
    title:{
    text:"Sales in Million $"
    }
    },
    series: []
    }
   
  

  ngOnInit() {
  

  }
 
getChartData(res:Response){

  this.orders=res['page']['data'];
 
  const data=this.orders.map(o =>o.total);
 
  const formattedOrders=this.orders.reduce((r,e) => {
   
    r.push([moment(e.placed).format('YY-MM-DD'),e.total]);
    return r;
  },[]);
  const p=[];

  console.log('formattedOrders:',formattedOrders);
  const chartData=formattedOrders.reduce((r,e)=>{
    const key=e[0];
if(!p[key]){
  p[key]=e;
  r.push(p[key]);
}else {
  
  p[key][1]+=e[1];
  
}
return r;
  },[]);
return chartData;
}
}

sales-data-service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs';
import { Order } from '../shared/order';

@Injectable({
  providedIn:'root'
})
export class SalesDataService {

  constructor(private _http: Http) { }

  
  getOrders( pageIndex: number, pageSize: number
    ) {
    return this._http.get('http://localhost:5103/api/order/'+ pageIndex + '/' + pageSize
    )
      .map(res => res.json());
  }
  
  
     }

orderController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Advantage.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Advantage.Api.Controllers
{
    [Route("api/[controller]")]
    public class OrderController : Controller
    {
        private readonly ApiContext _ctx;

        public OrderController(ApiContext ctx)
        {
            _ctx = ctx;

        }
        //Get api/order/pageNumber/pageSize
        [HttpGet("{pageIndex:int}/{pageSize}")]

        public IActionResult Get(int pageIndex, int pageSize)
        {
            //we pass the entire set of data that we get back when we we make a query for all the orders 
            var data = _ctx.Orders.Include(o => o.Customer)
                .OrderByDescending(c => c.Placed);
            //we pass the page index and pageSize
            var page = new PageResponse<Order>(data, pageIndex, pageSize);

            //
            var totalCount = data.Count();
            //use to determine total number of pages that exist in our response 

            var totalPages = Math.Ceiling((double)totalCount / pageSize);

            var response = new
            {
                Page = page,
                TotalPages = totalPages
            };
            return Ok(response);
        }
        //return all the orders grouped by state 
        [HttpGet("ByState")]
        public IActionResult ByState()
        {
            //we are getting all the orders from the system and include the customerOrder  so every order has a customer
            //and customer is a complex object that has a state 
            var orders = _ctx.Orders.Include(o => o.Customer).ToList();
            //we got back the orders and group them by state
            //we call toList to have that object in memory and select a new object
            //
            var groupedResult = orders.GroupBy(o => o.Customer.State).ToList()
                .Select(grp => new
                {
                    State = grp.Key,
                    Total = grp.Sum(x => x.Total)
                }).OrderByDescending(res => res.Total).ToList();

            return Ok(groupedResult);
        }
        //return all the orders grouped by customer 
        [HttpGet("ByCustomer/{n}")]
        public IActionResult ByCustomer(int n)
        {
            
            var orders = _ctx.Orders.Include(o => o.Customer).ToList();
            
            var groupedResult = orders.GroupBy(o => o.Customer.Id).ToList()
                .Select(grp => new
                {
                    Name =_ctx.Customers.Find(grp.Key).Name,
                    Total = grp.Sum(x => x.Total)
                }).OrderByDescending(res => res.Total).Take(n).ToList();

            return Ok(groupedResult);
        }
        //get order by id
        [HttpGet("GetOrder/{id}",Name="GetOrder")]

        public IActionResult GetOrder(int id )
        {
            var order=_ctx.Orders.Include(o => o.Customer).First(o => o.Id == id);
            return Ok(order);
        }


    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Advantage.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Advantage.Api.Controllers
{
    [Route("api/[controller]")]
    public class OrderController : Controller
    {
        private readonly ApiContext _ctx;

        public OrderController(ApiContext ctx)
        {
            _ctx = ctx;

        }
        //Get api/order/pageNumber/pageSize
        [HttpGet("{pageIndex:int}/{pageSize}")]

        public IActionResult Get(int pageIndex, int pageSize)
        {
            //we pass the entire set of data that we get back when we we make a query for all the orders 
            var data = _ctx.Orders.Include(o => o.Customer)
                .OrderByDescending(c => c.Placed);
            //we pass the page index and pageSize
            var page = new PageResponse<Order>(data, pageIndex, pageSize);

            //
            var totalCount = data.Count();
            //use to determine total number of pages that exist in our response 

            var totalPages = Math.Ceiling((double)totalCount / pageSize);

            var response = new
            {
                Page = page,
                TotalPages = totalPages
            };
            return Ok(response);
        }
        //return all the orders grouped by state 
        [HttpGet("ByState")]
        public IActionResult ByState()
        {
            //we are getting all the orders from the system and include the customerOrder  so every order has a customer
            //and customer is a complex object that has a state 
            var orders = _ctx.Orders.Include(o => o.Customer).ToList();
            //we got back the orders and group them by state
            //we call toList to have that object in memory and select a new object
            //
            var groupedResult = orders.GroupBy(o => o.Customer.State).ToList()
                .Select(grp => new
                {
                    State = grp.Key,
                    Total = grp.Sum(x => x.Total)
                }).OrderByDescending(res => res.Total).ToList();

            return Ok(groupedResult);
        }
        //return all the orders grouped by customer 
        [HttpGet("ByCustomer/{n}")]
        public IActionResult ByCustomer(int n)
        {
            
            var orders = _ctx.Orders.Include(o => o.Customer).ToList();
            
            var groupedResult = orders.GroupBy(o => o.Customer.Id).ToList()
                .Select(grp => new
                {
                    Name =_ctx.Customers.Find(grp.Key).Name,
                    Total = grp.Sum(x => x.Total)
                }).OrderByDescending(res => res.Total).Take(n).ToList();

            return Ok(groupedResult);
        }
        //get order by id
        [HttpGet("GetOrder/{id}",Name="GetOrder")]

        public IActionResult GetOrder(int id )
        {
            var order=_ctx.Orders.Include(o => o.Customer).First(o => o.Id == id);
            return Ok(order);
        }


    }
}

来源:https://stackoverflow.com/questions/63129060/fetch-data-from-asp-net-into-highchart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!