• 请不要在回答技术问题时复制粘贴 AI 生成的内容
chogath
V2EX  ›  程序员

向各位老哥请教下如何更合理的在 nest.js 中使用全局变量

  •  
  •   chogath · Feb 20, 2021 · 2022 views
    This topic created in 1928 days ago, the information mentioned may be changed or developed.

    以配置信息为例,nest.js 文档中提倡的是:注册 ConfigModule 并以依赖注入的方式,注入到其他模块中。

    这样的好处不言而喻,依赖关系和代码都非常清晰,但是如果我的 nest.js 项目中,需要在启动时调用配置中的信息呢?这样反而给我造成了困扰。

    我的想法是使用一个 store (实际上是一个闭包)来管理所有可能在全局需要用到的变量、客户端链接对象,在启动时注册,在需要时引入。

    以这样的方式注册好对应变量时,变量可以在任意地方引入。但是缺点是需要自行管理依赖。

    请各位老哥帮我指正,我还是个菜鸟...


    以上面理念设计的 demo: https://github.com/sophons-space/nest-server

    github issue: https://github.com/nestjs/nest/issues/6460

    stackoverflow: https://stackoverflow.com/questions/66291284/how-to-use-global-variables-in-nest-js

    Supplement 1  ·  Mar 16, 2021
    自己已经解决,还是用的依赖注入。在启动时在 ioc 上下文中获取提供者

    ## 以下是我自己认为的最佳实践
    ##---------------------------------------------------------
    https://github.com/sophons-space/nest-server
    https://github.com/sophons-space/nest-gateway
    https://github.com/sophons-space/nest-user-center

    ## end
    ##---------------------------------------------------------
    1 replies    2021-02-21 10:51:00 +08:00
    chogath
        1
    chogath  
    OP
       Feb 21, 2021
    -0-?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5497 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 93c8b4a0 · 43ms · UTC 07:54 · PVG 15:54 · LAX 00:54 · JFK 03:54
    ♥ Do have faith in what you're doing.