Angular and Plotly: Method that provides data get called too often

471 views Asked by At

I have a very simple Plotly graph in an Angular component:

<plotly-plot [data]="getTemperatureData()" [layout]="getTemperatureLayout()" [config]="displayModeBar: false}"></plotly-plot>

The getTemperatureData() method returns an object containing the data - standard procedure. However, that method gets called over and over again, even if the data are not updated. For example, hovering over the Plotly graph or Angular input fields triggers the method. Is there a way to only call the method when the data actually change?

1

There are 1 answers

2
Will Alexander On

I disagree with your suggestion that using a method to return data in the template is "standard procedure".

Why? Because that method gets called for every change detection cycle. This is, in fact, normal Angular behaviour.

As opposed to using a method, I suggest you use an Observable and the async pipe. That way, no matter how your getTemperatureData() method works, your template will always have the latest version of the data.

Extra tip: use *ngIf="temperatureData$ | async as temperatureData" to:

  • only display the graph when the data are present
  • give yourself an alias to the last emission of the data, allowing you to use it as though it were a "normal" variable