【问题标题】:NestJS: New instance of HttpModule per module importNestJS:每个模块导入的 HttpModule 新实例
【发布时间】:2020-06-04 13:26:46
【问题描述】:

我的nestjs系统是一个通过API调用连接多个系统的系统。

对于每个系统,我创建了一个模块来处理它们的进程。这些模块中的每一个都导入HttpModule

我想为每个模块的 HttpModule 设置单独的 Axios 拦截器。

这是我测试功能的尝试:

a.module.ts:

@Module({
  imports: [
    HttpModule,
    // Other imports
  ],
  // controllers, providers and exports here
})
export class ModuleA implements OnModuleInit {
  constructor(private readonly httpService: HttpService) { }
  public onModuleInit() {
    this.httpService.axiosRef.interceptors.request.use(async (config: Axios.AxiosRequestConfig) => {
      console.log('Module A Interceptor');    
      return config;
    });
  }
}

模块 B 的模块类类似,在 console.log 调用中的消息不同。

我尝试使用模块 B 中的服务对系统 B 进行 http 调用,但两条消息都显示在控制台中。

我认为 http 模块是整个系统的单例,那么如何为模块 A 和模块 B 实例化一个单独的 HttpModule

【问题讨论】:

    标签: typescript axios nestjs


    【解决方案1】:

    在阅读了Dynamic Modulesthis bug report 的文档后,发现在导入中调用register() 方法会创建一个单独的HttpModule 实例。

    所以我的解决方案是调用register() 并在两个模块的@Module 声明中传入一个空对象。

    @Module({
      imports: [
        HttpModule.register({}),
      ],
      // providers and exports
    })
    

    我不确定这是否是正确的做法,但它似乎有效。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 1970-01-01
      • 2021-11-06
      • 2022-11-14
      • 2018-10-08
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多