While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that when I tried to save this count as a public variable within the service, it returned undefined when accessed from another component.
I suspect that this is happening because the variable is being accessed before the observable is subscribed to, but I'm unsure how to resolve this issue.
In the code snippet below, you can see that I am trying to use _counts to store the frequency of each type, which works well within the getPciInfo method. However, when I try to access it from outside, it returns undefined (I need to pass this count to a different component).
Any help or advice on how to solve this problem would be greatly appreciated.
public _counts: any;
getPciInfo(): Observable <Ipcidata[]> {
return this.httpClient.get<Ipcidata[]>('http://dr0-hlp-07/api/PCIMachines')
.pipe(
map(results => {
const sorted = results.sort((a, b) => {
const updateDateA = Date.parse(this.datepipe.transform(a.UpdatedDate, 'MM-dd-yyyy'));
const carda = determineCardType(a, this.dateMinusMonth, this.dateMinusTwoWeeks)
const cardb = determineCardType(b, this.dateMinusMonth, this.dateMinusTwoWeeks)
return cardb - carda
});
this._counts = sorted.reduce((acc, cur)=>{
const cardType = determineCardType(cur, this.dateMinusMonth, this.dateMinusTwoWeeks)
switch (cardType) {
case 1:
acc.green += 1;
break;
case 2:
acc.yellow += 1;
break;
case 3:
acc.red += 1;
break;
}
return acc;
}, {
red: 0,
green: 0,
yellow: 0
});
console.log(this._counts)
console.log(this._counts.red)
return sorted;
}