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.
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.
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,
};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With