ngx-chart: Показать данные в реальном времени, угловой 4.3


я хочу визуализировать некоторые данные в реальном времени в ngx-chart-gauge.
Я создаю это с помощью этой демонстрации: https://swimlane.gitbooks.io/ngx-charts/content/v/6.0.2/charts/gauge.html
Я получаю свои живые данные из Сервиса и хочу показать данные в ngx-chart-gauge. Я получаю данные из службы ClassdataproviderService, которая сохраняет объекты в массиве 'single'.
Это мой компонент ngx-chart-gauge:

import {Component, OnInit, OnChanges, AfterViewInit, AfterViewChecked, AfterContentChecked, AfterContentInit, NgModule} from '@angular/core';
import {NgxChartsModule} from '@swimlane/ngx-charts';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {BrowserModule} from '@angular/platform-browser';
import {TempdatagiaService} from '../paho/tempdatagia.service';
import {ClassdataproviderService} from '../mqtt/classdataprovider.service';
import * as d3 from 'd3';

@Component({
  selector: 'app-mqtt',
  templateUrl: './mqtt.component.html',
  styleUrls: ['./mqtt.component.css']
})
export class MqttComponent implements OnChanges {

  view: any[] = [700, 400];
  data: any[];
  multi: any[];
  autoScale = true;

  constructor(private classdataproviderServie: ClassdataproviderService) {
  }


  ngOnChanges() {

      this.data = this.classdataproviderServie.single;

  }



  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C']
  };

  onSelect(event) {
    console.log(event);
  }
}

Это ngx-chart-gauge.html.

<ngx-charts-gauge
  [view]="view"
  [scheme]="colorScheme"
  [results]="data"
  [min]="0"
  [max]="100"
  [angleSpan]="240"
  [startAngle]="-120"
  [units]="'Temperature'"
  [bigSegments]="10"
  [smallSegments]="5"
  (select)="onSelect($event)">
</ngx-charts-gauge>

А это мой Сервис, откуда я получаю данные:

import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import {Paho} from '../../../node_modules/ng2-mqtt/mqttws31';




@Injectable()
export class ClassdataproviderService {

  public name: string;
  public value: string;

  single = [
    {
      name: '1',
      value: '15'
    },
    {
      name: '2',
      value: '20'
    }/*,
    {
      name: '3',
      value: '73'
    }*/
  ];



// Create a client instance
  client: any;
  packet: any;

  constructor() {



    // this.client = new Paho.MQTT.Client('broker.mqttdashboard.com', 8000,  'clientId-FUp9rr6sZS');
    this.client = new Paho.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080, 'Steffen');

    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }

  // called when the client connects
  onConnected() {
    console.log('Connected');
    this.client.subscribe('node/m1/temperature');
    //this.sendMessage('HelloWorld');
  }

  sendMessage(message: string) {
    const packet = new Paho.MQTT.Message(message);
    packet.destinationName = 'node/m1/temperature';
    this.client.send(packet);
  }

  // called when a message arrives
  onMessage() {
    this.client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log('Message arrived : ' + message.payloadString);
      this.single.push({name: 'test', value: message.payloadString});
      console.log(this.single);
    };
  }

  // called when the client loses its connection
  onConnectionLost() {
    this.client.onConnectionLost = (responseObject: Object) => {
      console.log('Connection lost : ' + JSON.stringify(responseObject));
    };
  }

Когда я пытаюсь ввести данные в датчик с помощью OnInit, датчик не обновляется. Чтобы решить эту проблему, я попробовал OnChanges, но теперь я получаю ERROR TypeError: Cannot read property 'big' of undefined ...
Я не знаю, возможно ли автоматическое обновление датчика без OnChanges или как избежать ошибки с помощью ловушки жизненного цикла OnChanges?


person Steffn    schedule 11.10.2017    source источник
comment
Вы пробовали использовать eventEmitter? Или обновление значений через BehaviourSubject?   -  person t3__rry    schedule 11.10.2017
comment
Я бы предложил передать данные на диаграмму через наблюдаемое с помощью асинхронного канала   -  person Jota.Toledo    schedule 11.10.2017


Ответы (2)


Теперь я опробовал множество решений, и наиболее эффективным было использование наблюдаемого, чтобы наблюдать за моей службой, откуда я получаю данные. Сервис, который вводит данные в компонент ngx-chart с наблюдаемым, выглядит так:

import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import {Paho} from '../../../node_modules/ng2-mqtt/mqttws31';
import 'rxjs/add/observable/interval';
import {AddDataService} from './datawindow/addmqtt/formmqtt/addmqtt.service';

@Injectable()
export class ClassdataproviderService {
  public name: string;
  public value: string;

  single = [
    {
      name: '',
      value: ''
    }
  ];

// Create a client instance
  client: any;
  packet: any;

  constructor() {

   this.addDataService.componentMethodCalled$.subscribe(
  () => {
    this.client = new Paho.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080, 'Steffen');
    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }}

  // called when the client connects
  onConnected() {
    console.log('Connected');
    this.client.subscribe('node/m1/temperature');
    //this.sendMessage('HelloWorld');
  }

  sendMessage(message: string) {
    const packet = new Paho.MQTT.Message(message);
    packet.destinationName = 'node/m1/temperature';
    this.client.send(packet);
  }

  // called when a message arrives
  onMessage() {
    this.client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log('Message arrived : ' + message.payloadString);
      this.single.push({name: 'test', value: message.payloadString});
      console.log(this.single);
    };
  }

  // called when the client loses its connection
  onConnectionLost() {
    this.client.onConnectionLost = (responseObject: Object) => {
      console.log('Connection lost : ' + JSON.stringify(responseObject));
    };
  }

Теперь единственный массив будет обновляться каждый раз, когда я получаю новые данные, и он отлично работает с ngx-диаграммами. И используйте ngOnInit как жизненный цикл в компоненте gauge.

person Steffn    schedule 04.12.2017

вы пытаетесь изменить данные не распознается функцией обнаружения изменений.

 this.data = this.classdataproviderServie.single;

вместо этого попробуйте распределить данные, чтобы обнаружить изменения. У меня это сработало.

 this.data = [...this.classdataproviderServie.single];
person Thanan_Jaje    schedule 18.03.2020
comment
Да, всегда клонируйте массив результатов, когда хотите обновить данные. - person Gihanmu; 28.11.2020