从nodejs服务获取的数据以角度2动态更新图表js图表

时间:2017-09-24 12:51:14

标签: javascript angular chart.js

HTML文件

我想在每10秒钟后更新chart.js生成的图表而不重新加载页面。在这里我使用getTankData()从后端获取所有数据并更新图形元素但是图形直到我才更新重新加载页面。但我想自动更新它而不重新加载。

<div class="container">

    <div class="row">
    <div class="col-md-3">
      <h2>User Water Graph</h2>

    </div>
      <div class="col-md-9">
        <div style="display: block;">
        <canvas id="myChart" baseChart *ngIf="time_data && water_data.length > 0"
          width="700" height="400"
                    [datasets]="lineChartData"
                    [labels]="lineChartLabels"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"></canvas>
        </div>
      </div>

    </div>
  </div>

TypeScript文件

import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {Router} from '@angular/router';
import {FlashMessagesService} from 'angular2-flash-messages';


@Component({
  selector: 'app-admin-dashboard',
  templateUrl: './admin-dashboard.component.html',
  styleUrls: ['./admin-dashboard.component.css']
})
export class AdminDashboardComponent implements OnInit {
  total_tank_data:any;
  time_data:Array<any>;
  water_data:Array<any>;
  lineChartData:Array<any> = []
  lineChartLabels:Array<any>
  lineChartOptions:any
  lineChartColors:Array<any>
  lineChartLegend:boolean
  lineChartType:string
  data_length:any

  constructor(
    private authService:AuthService,    
    private flashMessage:FlashMessagesService,
    private router:Router,) { }

  ngOnInit() {

    this.getTankData()
    if(localStorage.getItem('type')=='user'){
      this.authService.userAccess = true
    }
    else{
      this.authService.adminAccess = true
    }

  }


  getTankData(){
    var i;
    console.log(document.getElementById('chart'));
    this.authService.getTank().subscribe(data=>{
      this.time_data = [];
      this.water_data = [];
      this.total_tank_data = [];
      this.total_tank_data = data['tank'];
      this.lineChartData = [];
      this.lineChartLabels = [];
      for(i=0;i<this.total_tank_data.length;i++ ){
        this.time_data[i] = String(this.total_tank_data[i]['timestamp']);
        this.water_data[i]=parseInt(this.total_tank_data[i]['liters']);
      }

      this.lineChartData=[
        {data: this.water_data, label: 'Tank'}
      ];

      this.lineChartLabels= this.time_data;

      console.log(this.lineChartLabels)
      this.lineChartOptions= {
        responsive: true
      };
      this.lineChartColors = [
        { // grey
          backgroundColor: 'rgba(64,164,223,0.6)',
          borderColor: 'rgba(148,159,177,1)',
          pointBackgroundColor: 'rgba(148,159,177,1)',
          pointBorderColor: '#fff',
          pointHoverBackgroundColor: '#fff',
          pointHoverBorderColor: 'rgba(148,159,177,0.8)'
        },

      ];
      this.lineChartLegend= true;
      this.lineChartType= 'line';
      this.data_length = this.total_tank_data.length; 


    });
setInterval(()=>{
this.getTankData();
location.reload()
},10000);
  }


}

2 个答案:

答案 0 :(得分:1)

在完成循环之前,新数据到达后端时始终显示空数组。所以请从您调用的函数中删除数组,并在开头启动空数组。

ngOnInit(){
this.time_data = [];
this.water_data = [];
 }

答案 1 :(得分:0)

你每10秒在哪里调用getTankData?

将其添加到您的TypeScript文件:

import { ChangeDetectorRef } from '@angular/core';


 constructor(private ref: ChangeDetectorRef){}

 ngOnInit(){

   //Call it every 10 seconds
   setInterval(this.getTankData(), 10000);
}



 //add an change detector at the end of your getTankData function

   getTankData(){
     ...
    this.ref.detectChanges();
    }