I am working on an Angular application, that listens to the MQTT broker. I am trying to parse the response with JSON.parse() function. It looks simple, but I can't get the correct data to my global variable.
I am publishing this data (id of light and rgb value of that light) :
[{"light":2,"color":{"r":150,"g":24,"b":24}},{"light":3,"color":{"r":150,"g":24,"b":24}},{"light":4,"color":{"r":150,"g":24,"b":24}},{"light":6,"color":{"r":150,"g":24,"b":24}},{"light":7,"color":{"r":150,"g":24,"b":24}}]
The code looks like this.
export class LightsComponent implements OnDestroy {
lightsValues;
private subscription: Subscription;
constructor(private mqttService: MqttService) {
this.subscription = this.mqttService.observe(TOPIC).subscribe((message: IMqttMessage) => {
this.lightsValues = JSON.parse(message.payload.toString());
console.log(JSON.parse(message.payload.toString()));
console.log(this.lightsValues);
});
}
The result of console.log is the weird part, as I am only assigning the same JSON.parse() to the variable as into the console.log - https://i.stack.imgur.com/pj8BY.jpg
As you can see, the light parameter is set to 0 for all objects, rgb is set correctly.
However, when I change the lightsValues variable to local like this, I get the correct data.
export class LightsComponent implements OnDestroy {
lightsValues;
private subscription: Subscription;
constructor(private mqttService: MqttService) {
this.subscription = this.mqttService.observe(TOPIC).subscribe((message: IMqttMessage) => {
let lightsValues = JSON.parse(message.payload.toString());
console.log(JSON.parse(message.payload.toString()));
console.log(lightsValues);
});
}
With this code, the data is correct in both console.logs - https://i.stack.imgur.com/Lbl2E.jpg
I need to get this correct data to my global variable, as it serves as an @Input for my other component.
<app-lights-preview [lightsValues]="lightsValues"></app-lights-preview>
The child component :
export class LightsPreviewComponent {
@Input() lightsValues;
.
.
.