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

Him*_*shu 2 firebase ng2-charts angular

我对angular2完全不熟悉.我的问题是我通过ng2-charts lib创建了一个条形图,并使用angularfire2将其链接到firebase.我有2个组件和一个服务,用于向我的firebase数据库发送和接收数据.我可以doctor-local.component.ts通过my 将一个组件中的数据发送到firebase,data.service.ts并在我的接收上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);
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

这是我的 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Him*_*shu 7

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

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

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

asyncFnWithCallback()你的功能在哪里

然后在您的html中,用以下内容包装整个图表模板:

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

在这种情况下,for 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)