Chartjs-Realtime data from a service in ionic / angular

1๐Ÿ‘

โœ…

You can use Observable or Subject to listen data stream in realtime.
Your your socket service probably will be like below.

export class MqttService {
private mqttClient:any;//any mqtt implementation library
  connect(params:any): {
    this.mqttClient = mqtt.connect('connection url');
  }
  onTopic(topic: string,header:any): Observable<any> {
  //subscribe any topic here.
    return Observable.create((observer) => {
          this.mqttClient.observe(topic).subscribe((message) => {
              observer.next(JSON.parse(message.payload.toString()));
            },header);
    });
  }
}

After you wrote your service, use it inside any component you wish.

export class Tab1Page {

@ViewChild("barCanvas", { static: true }) barCanvas: ElementRef;
private barChart: Chart;

constructor(private mqttService:MqttService){}

ngOnInit() {
    this.barChart = new Chart(this.barCanvas.nativeElement)//no idea how to init this Class,
  this.mqttService.onTopic("app/chart").subscribe(data=>{
     this.refreshChart(this.barChart,data)
   })
}

 refreshChart(chart:Chart,data){
 //refresh the chart
 }

}

Leave a comment