Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project

I have written a service as shown below:

export interface ConfigData {
    DB_NAME:        string;
}

@Injectable()
export class ConfigManager {
    private static _instance?: ConfigManager;
    public static configData:ConfigData | null;
    private constructor() {
        console.log(ConfigManager)
        if (ConfigManager._instance)
            ConfigManager._instance = this;
        else{
            ConfigManager._instance = new ConfigManager()
            ConfigManager.configData = <ConfigData|null><unknown>ConfigManager.fetchSecretData()
        }
    }
    private static async fetchSecretData():Promise<ConfigData|null>{
        // some data from db
    }
    // static get instance() {
    //     return ConfigManager._instance ?? (ConfigManager._instance = new ConfigManager());
    //     //return ConfigManager._instance ?? (ConfigManager._instance = ConfigManager.fetchSecretData()) //new ConfigManager());
    // }
    
}

configuration.module.ts

@Global()
@Module({
    providers: [ConfigManager],
    exports: [ConfigManager],
})
export class ConfigurationModule {}

Within app.module.ts, I included ConfigurationModule in the imports section.

However, upon adding a private constructor to the service, it prevented me from including it in the module.ts file.

My expectation was that I would be able to access configData from anywhere without having to import ConfigManager. Unfortunately, this is not functioning as intended...

The issue lies in the fact that ConfigManager is inaccessible without importing it first.

Answer №1

If you've only used the @Global decorator on your module in NestJS, it's important to also include that module in your core application module for it to be globally accessible.

To achieve this, simply add your module to your core application module like so (or whatever your root module is named):

@Module({
  imports: [ConfigurationModule],
})
export class AppModule {}

You can refer to the documentation for more information.

The @Global() decorator defines the module as global-scoped. Global modules should typically be registered once, usually within the root or core module of the application.

Answer №2

By utilizing global modules within Nest, you eliminate the need to repeatedly include that module in the imports: [] section of every other module that requires its providers. The providers within the global module function just like normal providers, meaning you still have to inject them where they are needed.

In your specific scenario, since you have marked ConfigManager with @Global() and imported ConfigurationModule in app.module.ts, there is no requirement to add ConfigurationModule in the imports for any other modules that wish to utilize ConfigManager. However, you will still need to inject the ConfigManager provider - this is indicated by using @Injectable().

To perform the injection, you must have a

constructor(private configManager: ConfigManager) {}
within the class that requires access to ConfigManager. Additionally, since you need to know the type of the class, you will also need to
import { ConfigManager } from '../path/to/ConfigManager'
.

Answer №3

In the realm of ES6/TS, it is essential to import a class before using it in your code.

It seems like you may be confusing dependency injection (instantiation/composition) with importing classes into the module's scope.

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

Injecting cascading style sheets across different domains using Javascript

Put simply: Is it possible for an external Javascript code to inject another script that is hosted on a completely different domain into the page's Document Object Model (DOM)? For example: Imagine the website foo.com which has an html script tag w ...

The D3.extent() function is raising a TypeError because it is unable to iterate over the

I have been struggling with this issue for the past few hours, and I could really use some help. I'm not very familiar with using D3 in conjunction with React. Essentially, I have an anomaly detection algorithm running on the backend Flask App that r ...

Is it possible to incorporate a PHP line within a Handlebars context array?

I'm currently utilizing handlebars along with a handlebars register helper to iterate through an array that I've included in my context. The result is then displayed as an unordered list (ul). However, I'm facing an issue when attempting to ...

An issue occurred in resolving dependencies for the UsersService in Nest

I've been experimenting with Nest a bit, attempting to create a module that I can publish on my private repository for reuse in future projects. However, I've run into an error: ERROR [ExceptionHandler] Nest can't resolve dependencies of the ...

What steps are needed to successfully enable the callback function within the addFilter method from @wordpress/hooks while customizing the tables in WooCommerce analytics reports?

I've been diving into customizing Analytics reports tables for clients on our WooCommerce platform. I followed a guide at this link, but encountered an issue with the JavaScript file. After adding the filter at the end of the file as instructed, noth ...

Utilize the context API to efficiently share information from the parent to both its children and sibling children

I'm currently working on displaying fetched data in a child component using the context API, but encountering an error in the browser: TypeError: render is not a function The above error occurred in the component: in AppDataList (at App.j ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

Ways to "Compile out" log commands

In my typescript project, there is a section of code dedicated to creating debug information. However, upon profiling the application, I discovered that this debug code is causing a significant performance impact. Currently, my approach involves setting a ...

Tips for verifying blank form fields

Is there a way to validate empty form fields before submission and show an alert? This validation is important as some fields are hidden using v-show. Here is an example: <!DOCTYPE html> <header> <script src="https://unpkg.com/vue@n ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

Is it considered acceptable to retrieve the action payload in mapDispatchToProps in a React/Redux setup?

In my MediaUpload component, I have a mapDispatchToProps function that handles file uploads. When a file is added, the onChange handler triggers two actions: creating new media entries for the files and updating the form data in the state with the generate ...

Making changes to a variable or option through the props in a different file

In the index.js file, I have implemented getStaticProps() to fetch data from an exported function. This function requires 2 parameters, one for the type of listing and the quantity. export async function getStaticProps() { const type = 0 const data = a ...

Using V-bind to assign multiple classes has never been easier

Is there a way to assign one of two classes to an element based on three possible input variables in my Vue.js code? <input type='text' class='inputwordtext' v-bind:class="{(wordupload.firstchoice.selected == 'Zinnenlijst' ...

Updating visual appearance with button clicks and unclicks

Is there a way to dynamically update the button image while clicking on it? This is what I have tried: $('.gamebox_minimap_plus').click(function() { $(this).css("background-image","url('gfx/plus2.png')"); }); The image ch ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

Error with setting innerHTML property of a null nested div

This issue arises when the element is referenced before the DOM has completely loaded. To combat this, I have ensured that the necessary script runs only after the window has finished loading. Interestingly, if the getElementById() call is for a standalon ...

Why does my React.js application still display outdated data from my Express server even after refreshing the webpage?

I have been working on a website using React.js and Express.js, following an online example to set up the basic code. I encountered an issue where the frontend did not update when I made a minor change to the array sent by Express.js. Express - users.js f ...

How come my $scope variables are not resetting when attempting to refresh the data?

I just started working with Angular and encountered an issue while trying to implement a reload button. My webpage displays a table with data pulled from a Parse database. The table can be modified using various buttons, and after making changes, I want to ...

How come the mouseover effect on the div remains even after the mouse has been removed?

How can I keep the original CSS class when the mouse moves away? function highlight( x, y) { var sel=document.getElementById(y); sel.style.borderBottom= "2px solid "+x; sel.style.opacity="1"; sel.style.transition="all eas ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...