Sunday, 28 November 2021

Globle module without import not working nestjs

I am trying to implement a global module in nest.js

I have created a service like 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 {}

and in app.module.ts added ConfigurationModule in imports.

Also adding private constructor on service unable it to add in module.ts file.

I am expecting that I should be able to configData anywhere without importing the ConfigManager. but it's not working...

ConfigManager is not available without import.



from Globle module without import not working nestjs

No comments:

Post a Comment