我有一个奇怪的问题,我无法理解。我将priceHistories
存储在内存中的数组中。当我调用一个get方法时,它不会返回相同的值,这取决于我从哪里调用该方法。
原始属性和方法:
@Injectable()
export class PricehistoryService {
private readonly logger = new Logger(PricehistoryService.name);
private priceHistories: PriceHistory[] = [];
getPriceHistories(): PriceHistory[] {
this.logger.log(this.priceHistories);
return this.priceHistories;
}
....
}
当从这个Controller
调用时,它返回完整的历史记录。
@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();
}
}
预期回报(在上面的Controller
调用上工作):
[
{
"naam": "karmeliet",
"prices": [
{
"price": "2.5",
"timestamp": 1683917722366
}
]
}
]
但是,当我从另一个Service
调用它时,它只返回一个空数组。getPriceHistories()
中的日志还显示this.priceHistories
是[]。
@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
这里是[]
编辑1:
显然,从PricesService
调用到PricehistoryService
或DrinksService
的任何方法都会返回一个空数组。当从其他Services
调用方法时不会发生这种情况,只有PricesService
。
1条答案
按热度按时间zlwx9yxi1#
显然,原因是我把
pricesService
放进了AppModule
的providers
。把它取下来就成功了。