如何通过firebase实时更新ng2-charts中的值

时间:2017-03-26 20:30:24

标签: angular firebase ng2-charts

我对angular2完全不熟悉。我的问题是我通过ng2-charts lib创建了一个条形图,并使用angularfire2将其链接到firebase。 我有2个组件和一个服务,用于向我的firebase数据库发送和接收数据。我能够通过我的doctor-local.component.ts将一个组件data.service.ts中的数据发送到firebase中,并在我的doctor-expert.component.ts上接收它,并使这里的数据与firebase数据库中的值保持同步并显示在使用(ngModelChange)事件绑定在同一组件中实时。条形图也在此组件中。

这是我的expert.component.tsdoctor-expert.component.html

import {Component} from '@angular/core';
import {DataService} from '../data.service';
import {FirebaseObjectObservable} from 'angularfire2';

@Component({
  selector: 'app-doctor-expert',
  templateUrl: './doctor-expert.component.html',
  styleUrls: ['./doctor-expert.component.css']
})
export class DoctorExpertComponent {
  public items: FirebaseObjectObservable<any>;
  
  public barChartOptions: any = {
    scaleShowVerticalLines: false,
    responsive: true
  };
  public barChartLabels: string[] = ['RBC Count', 'WBC Count', 'Haemoglobin'];
  public barChartType: string = 'bar';
  public barChartLegend: boolean = true;
  rbc: number;
  wbc: number;
  haemo: number;


  public barChartData: any[] = [
    {data: [75, 59, 80], label: 'Current Count'},
    {data: [28, 48, 40], label: 'Average Normal Count'}
  ];

  constructor(private dataService: DataService) {
    this.items = this.dataService.messages;
    this.items.subscribe(data => {
      this.rbc = parseInt((data.rbccount), 10);
      this.wbc = parseInt((data.wbccount), 10);
      this.haemo = parseInt((data.haemocount), 10);
    });
    this.barChartData = [
      {data: [this.rbc, this.wbc, this.haemo], label: 'Current Count'},
      {data: [50, 50, 50], label: 'Average Normal Count'},
    ];
  }

  
  public chartClicked(e: any): void {
    console.log(e);
  }

  public chartHovered(e: any): void {
    console.log(e);
  }
}
<ul class="list-group container">
  <li class="list-group-item">RBC Count: {{(items | async)?.rbccount}} </li>
  <li class="list-group-item">WBC Count: {{(items | async)?.wbccount}} </li>
  <li class="list-group-item">Haemoglobin Count: {{(items | async)?.haemocount}} </li>
</ul>

<div class="container">
  <div style="display: block">
    <canvas baseChart
            [datasets]="barChartData"
            [labels]="barChartLabels"
            [options]="barChartOptions"
            [legend]="barChartLegend"
            [chartType]="barChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
  </div>
</div>

这是我的data.service.ts

import {Injectable} from '@angular/core';
import 'rxjs/Rx';
import {AngularFire, FirebaseObjectObservable} from 'angularfire2';

@Injectable()
export class DataService {
  public messages: FirebaseObjectObservable<any>;

  constructor( public af: AngularFire ) {
    this.messages = this.af.database.object('data');
  }


  sendData(value1, value2, value3) {
    const message = {
      rbccount: value1,
      wbccount: value2,
      haemocount: value3
    };
    this.messages.update(message);
  }

  sendrbc(value){
    const message = {
      rbccount: value
    };
    this.messages.update(message);
  }

  sendwbc(value2){
    const message = {
      wbccount: value2
    };
    this.messages.update(message);
  }

  sendhaemo(value3){
    const message = {
      haemocount: value3
    };
    this.messages.update(message);
  }
}

“this.items = this.dataService.messages”从数据库接收代码,subscribe方法从observable获取值。现在我想更新barChartData中收到的这个值,并使其与数据库中的更改保持同步。因此,每次通过doctor-local.component.ts传递的数据发生变化时,数据库和条形图中的更改都会立即发生。我尝试在构造函数本身中执行此操作,但数据根本不会显示在条形图中,更不用说不断更​​新了。

1 个答案:

答案 0 :(得分:6)

我做了一些挖掘,并提出了这个非常直接的解决方案。 问题是数据集是异步加载的,并且在初始化时正在呈现图表,这就是为什么它无法加载新数据的原因。

解决方法是等待绘制画布,直到你的asyncs完成。在您的组件中:

isDataAvailable:boolean = false; ngOnInit() { asyncFnWithCallback(()=>{ this.isDataAvailable = true}); }

asyncFnWithCallback()是你的职能。

然后在你的html中,用:

包装你的整个图表模板

<div *ngIf="isDataAvailable"> . . . chart canvas + any other template code . . . </div>

在这种情况下,对于doctor-expert.component.ts,新代​​码如下所示:

import {Component, OnInit} from '@angular/core';
import {DataService} from '../data.service';
import {FirebaseObjectObservable} from 'angularfire2';

@Component({
  selector: 'app-doctor-expert',
  templateUrl: './doctor-expert.component.html',
  styleUrls: ['./doctor-expert.component.css']
})
export class DoctorExpertComponent{
  public items: FirebaseObjectObservable<any>;

  public barChartOptions: any = {
    scaleShowVerticalLines: false,
    responsive: true
  };
  public barChartLabels: string[] = ['RBC Count', 'WBC Count', 'Haemoglobin'];
  public barChartType: string = 'bar';
  public barChartLegend: boolean = true;
  rbc: number;
  wbc: number;
  haemo: number;


  public barChartData: any[] = [];

  isDataAvailable: boolean = false;

  constructor(private dataService: DataService) {
    this.items = this.dataService.messages;
    this.items.subscribe(data => {
      this.rbc = parseInt((data.rbccount), 10);
      this.wbc = parseInt((data.wbccount), 10);
      this.haemo = parseInt((data.haemocount), 10);
      this.barChartData = [
        {data: [this.rbc, this.wbc, this.haemo], label: 'Current Count'},
        {data: [50, 50, 50], label: 'Average Normal Count'},
      ];
      this.isDataAvailable = true;
    });
  }


  public chartClicked(e: any): void {
    console.log(e);
  }

  public chartHovered(e: any): void {
    console.log(e);
  }
}

doctor-expert.component.html看起来像这样:

<ul class="list-group container">
  <li class="list-group-item" (ngModelChanges)="update($event)">RBC Count: {{(items | async)?.rbccount}} </li>
  <li class="list-group-item" (ngModelChanges)="update($event)">WBC Count: {{(items | async)?.wbccount}} </li>
  <li class="list-group-item" (ngModelChanges)="update($event)">Haemoglobin Count: {{(items | async)?.haemocount}} </li>
</ul>

<div class="container" *ngIf="isDataAvailable">
  <div style="display: block">
    <canvas baseChart
            [datasets]="barChartData"
            [labels]="barChartLabels"
            [options]="barChartOptions"
            [legend]="barChartLegend"
            [chartType]="barChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
  </div>
</div>