The Scenario
In my angular 7 application, I am fetching data from a web API in JSON format. The app is functioning correctly, but I believe I am making excessive API calls and can optimize it to just one call.
Custom Class:
export class customClass {
constructor(tagname: string, value: number, description: string, units: string, quality: string, timestamp: string, lowlimit: number, highlimit: number, asset: string) {
this.tagname = tagname;
this.value = value;
this.description = description;
this.units = units;
this.quality = quality;
this.timestamp = timestamp;
this.lowlimit = lowlimit;
this.highlimit = highlimit;
this.asset = asset;
}
tagname: string;
value: number;
description: string;
units: string;
quality: string;
timestamp: string;
lowlimit: number;
highlimit: number;
asset: string;
}
dashboard.component.ts - within this file, there is an array of type customClass
.
mylist: customClass[];
The array is populated within the ngOnInit
using:
this._myService.getcurrentvalues()
.subscribe
(
(data: customClass[]) => this.mylist= data
);
Then, I display this array in the HTML component using:
<mat-card-content *ngFor="let com of myList">
This allows me to generate a line of text per entry in the list by referencing properties such as:
<p class="tag-description">{{com.description}}</p>
The Objective
I realize that I am calling the API multiple times for a single HTML component. To address this, I want to fetch all the data with a single API call and then manipulate it within the application for better performance.
The Challenge
To achieve this, I attempted to create a function in my dashboard.component.ts file which I could then iterate through in my HTML component. I intended to place this function outside of ngOnInit
. Here is what I tried:
get myData(){
let result : customClass[];
for(var item of Object.keys(this.myList)){
let item1 = this.myList[item]
for(var item2 of item1){
if (item2.asset == "someString")
{
var newObject : historiantags;
newObject.tagname = item2.tagname;
newObject.value = item2.value;
newObject.description = item2.description;
newObject.units = item2.units;
newObject.quality = item2.quality;
newObject.timestamp = item2.timestamp;
newObject.lowlimit = item2.lowlimit;
newObject.highlimit = item2.highlimit;
newObject.asset = item2.asset;
result.push(newObject);
}
}
}
return result;
}
Trying to display this in my HTML component using:
<mat-card-content *ngFor="let com of myData">
However, this setup resulted in the error:
item1 is not iterable
Is there a way to make this work or should I approach it differently?
*Update
To troubleshoot, I added the word debugger
to the myData
function, but it was never triggered. Additionally, adding {{com | json}}
to the HTML did not return anything, indicating that myData()
is not being called. How can I ensure that this function is executed?