[Fixed] Indicator to variable in array instead of variable in Angular

Issue

I have following part of my code:

private engineSpeed = 0;
private gearboxTemp = 0; 
private engine = {
  "Temp1" : ["30 °C", "30 °C", "30 °C"],
  "Param" : ["17.23 kPa", "1200 m³/min", "0.7 kg/m³", "55 °C"],
  "Speed" : [this.engineSpeed + " rpm"]
}


ngOnInit(): void {
  this.dataWatchdog = setInterval(async () => {  
    this.engineSpeed = await this.getEngineSpeed()
  }, 5000)
}


public button()
{
    console.log("Speed ", this.engine["Speed"])
    console.log("Engine speed", this.engineSpeed )
}

I am updating this.engineSpeed variable in each 5s in dataWatchdog. But still in engine array this.engineSpeed value is not updated and in console.log I am getting the 0.

Result in console

Is it possible to have an indicatior to this.engineSpeed variable in array instead of just a variable and keep it updated? Thanks in advance

Solution

Assigning a new value to this.engineSpeed doesn’t implicitly update the value of this.engine.Speed[0] because the this.engineSpeed + " rpm" is only interpreted once and contains a copy of the initial value of this.engineSpeed. You could update this.engine.Speed[0] imperatively in your "watchdog", create a getSpeed method or do something like this:

private engine = {
  // ...
  "Speed" : () => [this.engineSpeed + " rpm"] // Speed is now a function
}

public button()
{
    console.log("Speed ", this.engine["Speed"]())
    console.log("Engine speed", this.engineSpeed )
}

Leave a Reply

(*) Required, Your email will not be published