Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global variables in nest.js?

Taking configuration as an example, the Nest.js documentation advocates registering Config Modules and injecting them into other modules in a dependency injection way.

The benefits are obvious, and the dependencies and code are clear, but what if I have a nest.js project that needs to invoke the configuration information at startup? This actually caused me trouble.

My idea is to use a store (actually a closure) to manage all the variables that might be needed globally, the client-side link objects, registered at startup, and introduced when needed.

When corresponding variables are registered in this way, they can be introduced anywhere. The drawback is that you need to manage dependencies yourself.

With the above concept design of demo: https://github.com/sophons-space/nest-server.

Please e help me correct, I am still a rookie.

like image 535
yang.liu Avatar asked Jan 24 '23 11:01

yang.liu


2 Answers

Create a file global.service.ts (inside a folder you can name it utils or whatever) & put the code bellow

export class GlobalService{ 
   static globalVar: any; 
}

Set value to the globalVar

GlobalService.globalVar = 'some value';

Get value from globalVar

console.log(GlobalService.globalVar);

N.B. Don't forget to import GlobalService wherever you want to use.

like image 35
Musabbir Mamun Avatar answered Jan 27 '23 01:01

Musabbir Mamun


If you want to use Nest flow it should be defined in the configuration file

// app.module.ts
import configuration from './config/configuration';

imports: [
// first import as first initialization
  ConfigModule.forRoot({
    isGlobal: true, // to get access to it in every component
    load: [configuration],
  }),
]
...
// configuration.ts
export default (): any => {
  return {
    someGlobalConfigVariable: parseInt(process.env.PORT, 10) || 3000,
  };
};

like image 150
kosiakMD Avatar answered Jan 26 '23 23:01

kosiakMD