There is a puzzling issue that I am unable to solve. I have stored priceHistories
in memory within an array. Strangely, when I invoke a get method, the returned value varies depending on where the method is called from.
This is the original property and method setup:
@Injectable()
export class PricehistoryService {
private readonly logger = new Logger(PricehistoryService.name);
private priceHistories: PriceHistory[] = [];
getPriceHistories(): PriceHistory[] {
this.logger.log(this.priceHistories);
return this.priceHistories;
}
....
}
When the method is invoked from this Controller
, it returns the complete history
@Controller('pricehistory')
export class PricehistoryController {
private readonly logger = new Logger(PricehistoryController.name);
constructor(private readonly priceHistoryService: PricehistoryService) {}
@Get()
getCompletePriceHistory(): PriceHistory[] {
this.logger.log('GET REQUEST: Complete price history');
return this.priceHistoryService.getPriceHistories();
}
}
Expected return (functioning with the above Controller
call):
[
{
"naam": "karmeliet",
"prices": [
{
"price": "2.5",
"timestamp": 1683917722366
}
]
}
]
However, when called from another Service
, it simply returns an empty array. The log in the getPriceHistories()
also indicates that this.priceHistories
is [].
@Injectable()
export class PricesService {
private appSettings: AppSettings;
private readonly logger = new Logger(PricesService.name);
constructor(private readonly drinksService: DrinksService, private readonly priceHistoryService: PricehistoryService) {
this.appSettings = {factor: 10, standaardafwijking: 2, minimum: 0.6, maximum: 2.5}
}
getCurrentPrices(): CurrentPrice[] {
this.logger.log("Getting all current prices");
let currentPrices: CurrentPrice[] = [];
let priceHistories: PriceHistory[] = this.priceHistoryService.getPriceHistories();
priceHistories.forEach(priceHistory => {
let currentPriceTemp: CurrentPrice = {
naam: priceHistory.naam,
currentPrice: priceHistory.prices.at(priceHistory.prices.length - 1).price
};
currentPrices.push(currentPriceTemp);
})
return currentPrices;
}
....
priceHistories
here is []
EDIT 1:
Evidently, any method called from the PricesService
to either the PricehistoryService
or the DrinksService
results in an empty array being returned. This peculiar behavior only occurs when calling methods from the PricesService
.