在Angular 4中动态填充ng2图表

时间:2019-02-19 16:06:32

标签: angular charts ng2-charts

我编写了一个示例应用程序,以json格式从服务中获取数据并将其绑定到UI上的图表。

问题是,无论何时我尝试绑定数据,都没有。我尝试了多种方法来绑定数据,但未成功。

功能如下: 第1页:包含2个下拉菜单。图表类型为1,样本类型为2nd。 在选择两个下拉值后,我单击一个按钮,该按钮会触发GlobalService中的函数fetchData()。

以下是GlobalService中的获取和设置方法

 getChartData() {
  return this.chartData;
 }

 setChartData(response: any) {
   this.chartData = response.data;
   // console.log(this.chartData);
 }

 getChartlabel() {
  return this.chartLabel;
 }

 setChartLabel(response: any) {
   this.chartLabel = response.label.label;
   // console.log(this.chartLabel);
 }

 getResponse() {
   return this.response;
 }
 setResponse(response: any) {
   this.response = response;
   // console.log(response);
 }

函数像这样

 fetchData(chart: any, sample: any) {
  console.log();
  const request = {
    chartType: this.selectedChart, // 'BAR | LINE'
    sampleType: this.selectedSample // 'COUNT'
  };

  this.http.post('http://localhost:22222/school/getData', request, this.options)
    .subscribe(
      res => {
        res = res.json();
        const responseData = res;
        console.log(responseData);
        if (responseData.hasOwnProperty('data')) {
          console.log('Data Fetched');
          this.setResponse(responseData); // Setting response
          this.setChartData(responseData); // setting data
          this.setChartLabel(responseData); // setting label
          this.router.navigate(['/gotoChartPage']); // navigating to next page chart.html
        } else {
          alert('Data Fetch Failed');
        }
      });
 }

现在,我的chart.html看起来像here

中所述
<div id='barDiv' class="onerow" *ngIf="1">
        <h4 class="m-2">Bar Chart</h4>
    <div style="display: block">
        <canvas baseChart width="800" height="500"
                [datasets]="barChartData" // --> This is where i want to update Data
                [labels]="barChartLabels" // --> This is where i want to update Labels
                [options]="barChartOptions"
                [legend]="barChartLegend"
                [chartType]="barChartType">
          </canvas>
      </div>      

然后我的Chart.component如下

  /*******************BAR CHART*********************************/
  public barChartOptions: any = {
     scaleShowVerticalLines: false,
    responsive: true
  };

 public barChartLabels: Array<any> = []; // ["STD 1", "STD 2", "STD 3", "STD 4", "STD 5", "STD 6", "STD 7", "STD 8", "STD 9", "STD 10"]; Sample Data
 public barChartType  = 'bar';
 public barChartLegend  = true;
 public barChartData: any[]  = []; // [ {'data': [40, 32, 42, 23, 43, 35, 50, 48, 37, 45], label: 'COUNT'}]; -- Sample Data

 constructor(private global: GlobalService) {
  this.barChartData =  this.global.chartData;
  this.barChartLabels =  this.global.chartLabel;
}

我从json回复的格式如下:

对于单个数据集:

{
 "data":
    {"data": [40,32,42,23,43,35,50,48,37,45], "label":"COUNT"},
 "label":
    {"label":["STD 1","STD 2","STD 3","STD 4","STD 5","STD 6","STD 7","STD 8","STD 9","STD 10"]}
}

对于多个数据集:

{
 "data":
    {"data": [40,32,42,23,43,35,50,48,37,45], "label":"MVM"},
    {"data": [04,03,02,03,03,05,50,80,07,45], "label":"HVD"},
    {"data": [20,32,42,23,43,60,50,48,70,40], "label":"BMS"},
 "label":
    {"label":["STD 1","STD 2","STD 3","STD 4","STD 5","STD 6","STD 7","STD 8","STD 9","STD 10"]}
}

当我尝试以这种方式分配时,图表不会出现。但是,如果我对barChartLabels和barChartData中的值进行硬编码,则会显示图表。

我也以此方式尝试过

`<canvas baseChart width="800" height="500"
   [datasets]="global.chartData" // --> This is where I need to update Data
   [labels]="global.chartLabel" // --> This is where I need to update Labels
   [options]="barChartOptions"
   [legend]="barChartLegend"
   [chartType]="barChartType">
 </canvas>`

我们非常感谢您的帮助。我从大脑无法想象的范围内继续坚持下去。

我在堆栈上遇到了这个示例:CLICKCLICK但是,这不是正确的方法。

我想知道为什么数据不能像这样直接绑定到图表上

   [datasets]="global.chartData" // --> This is where I need to update Data
   [labels]="global.chartLabel"

1 个答案:

答案 0 :(得分:0)

您的全局服务将当前数据集保存在tf.Data.Iterator成员中,并且您在组件的构造函数中一次读取了该变量。但是,当数据更改时,将替换全局服务中的import { HttpClient, HttpHeaders } from "@angular/common/http"; constructor(private httpClient: HttpClient) {} httpOptions = { headers: new HttpHeaders({ "Content-Type": "application/json", Authorization: "API_KEY" }) }; createNewSubscriber() { this.httpClient .post( "https://endpoint", { name: this.data.form.manager.managerFirstName, last_name: this.data.form.manager.managerLastName, email: this.data.form.manager.managerEmail, external_id: this.data.managerUUID, group_id: `${this.data.form.companyName}${this.data.form.teamName}` }, this.httpOptions ) .subscribe( data => { console.log("POST Request is successful ", data); }, error => { console.log("Error", error); } ); }; 成员,但是组件中的成员会一直指向原始成员,因此您永远不会看到更改。

您可以在全局服务中使用可观察的流,以将数据更改通知客户端。