2017-10-10 79 views
0


我想在一個名爲'single'的數組中保存溫度數據(我從一個paho客戶端獲得)。最後,我想在儀表中顯示實時數據。
爲此,我創建了一項服務來存儲數據並將數據分發給多個組件。
但我只得到錯誤:「」不能分配給類型'{值:字符串; }」。
我真的很感激這個新想法!謝謝!從paho客戶端保存數據,角4

我的服務:

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: 'eins', 
     value: '15' 
    }, 
    { 
     name: 'zwei', 
     value: '20' 
    }, 
    { 
     name: 'drei', 
     value: '73' 
    } 
    ]; 


// Create a client instance 


    client: any; 
    packet: any; 

    constructor() { 
    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 = 'World'; 
    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('test', message.payloadString); **//<-- Here i want to push the data in my array** 
    }; 
    } 

    // called when the client loses its connection 


    onConnectionLost() { 
    this.client.onConnectionLost = (responseObject: Object) => { 
     console.log('Connection lost : ' + JSON.stringify(responseObject)); 
    }; 
    } 

回答

2

我解決了這個問題。
你只需要通過在onMessageArrived功能使用這條線來推動陣列(單)中的數據:

this.single.push({name: 'test', value: message.payloadString});