NestJs Function yielding inconsistent results based on its calling location

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.

Answer №1

It turns out that by placing the pricesService in the AppModule's providers, it was causing an issue. Once I removed it, everything worked smoothly.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ScheduleModule } from '@nestjs/schedule';
import { CronService } from './cron/cron.service';
import { DrinksModule } from './drinks/drinks.module';
import { PricehistoryModule } from './pricehistory/pricehistory.module';
import { PriceModule } from './price/price.module';
import { PriceController } from './price/price.controller';

@Module({
  imports: [
    ScheduleModule.forRoot(),
    DrinksModule,
    PricehistoryModule,
    PriceModule
  ],
  controllers: [AppController, PriceController],
  providers: [AppService, CronService]
})
export class AppModule {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...

Material-UI: Error thrown when attempting to pass props to makeStyles in React due to missing property 'X' on type '{}'

Currently experimenting with Adapting based on props, you can find more information here import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles({ // style rule foo: props => ( ...

Toggling multiple ions simultaneously does not function independently

I encountered a problem while working on an ionic app. I needed to have individual control over toggle switches, but my current code toggles all switches at once whenever one switch is tapped. Is there a way to fix this and manage each toggle switch separa ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Angular - Showing validation messages post successful execution of two functions

I have encountered an issue with my form submission process involving two functions. When both functions succeed, I want to display a successful validation message. However, currently the success message is displayed even if the second function fails. How ...

Issue: Catching errors in proxy function calls

I am currently using Vue 3 along with the latest Quasar Framework. To simplify my API calls, I created an Api class as a wrapper for Axios with various methods such as get, post, etc. Now, I need to intercept these method calls. In order to achieve this ...

Can you identify the specific syntax for a 'set' function in TypeScript?

I have a TypeScript function that looks like this: set parameter(value: string) { this._paremeter = value; } It works perfectly fine. For the sake of completeness, I tried to add a type that specifies this function does not return anything. I experimen ...

Guide on obtaining Elastic search documents in the specified order of identifiers

Given a specific order of document IDs [1, 4, 2, 5] and some filtering criteria { match: {...} }, what is the most efficient method to ensure that the resulting documents are retrieved in the desired order [1, 4, 2, 5]? Here is an example of a sample docu ...

A guide to implementing typescript with Next.js getStaticProps

I have Next.js set up with the TypeScript feature enabled Currently, I am attempting to utilize the getStaticProps function following the guidelines outlined here: https://nextjs.org/docs/basic-features/typescript Utilizing the GetStaticProps type export ...

TypeScript requires that the `includes` function must have the same type parameter for both input and

When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of ...

What is the best method for accessing a store in Next.js with Redux Toolkit?

Currently, I am working on incorporating integration testing for my application using Jest. To achieve this, I need to render components in order to interact with various queries. However, in order to render a component, it must be wrapped in a Provider to ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab. This is my userlog.component.ts file: import { Component, OnInit, O ...

The JSX component in next.js cannot be utilized as a user component

I am facing difficulty in getting my mobile menu to function properly. Initially, I attempted to position it above other content using the useEffect hook, but unfortunately, it resulted in breaking the entire project. This is the error message I encountere ...

Mastering Props Typing in React Using TypeScript

Currently, I am faced with the task of defining the following: interface MyCompProps { someAttr: number } Instead of having to explicitly list all the aria-* attributes I need upfront, I would like to simply use aria- and other normal HTML attributes ...

The value of form.formGroup is not equivalent to the output of console.log(form)

Having an issue here. When I send a Form to a component, If I use console.log(form), it displays the object correctly. However, when I check the form in the console, the form.formGroup.value looks fine (e.g. {MOBILE0: 'xxx', PHONE0: 'xxx&ap ...

Binding an ID to an <ion-textarea> in Ionic 3

Can an ID be assigned to an ion-textarea? For example: <ion-textarea placeholder="Enter your thoughts" id="thoughtsBox"></ion-textarea> Thank you very much ...

Exploring Angular 10 Formly: How to Retrieve a Field's Value within a Personalized Formly Wrapper

Utilizing Angular 10, I have a formly-form with a select-field named session. This select field provides options from which to choose a dndSession. Each option holds key-value pairs within an object. I want to add a button next to the select-field that tr ...

Retrieving the name of the current page in ionViewCanEnter

While working with Ionic 2, I am currently facing a challenge in identifying the name of the page that triggered the navigation (PUSHER) before entering the destination page (PUSHEE). Within the PUSHEE page, I have an ionViewCanEnter function where I need ...

Creating personalized mapping for TypeScript objects

I have a TypeScript object structure that resembles the following: { "obj1" : { object: type1;}; "obj2" : { object: type2;}; "obj3" : { object: type3;}; "obj4" : { object: type4;}; "obj5" ...