NestJS:每个模块导入的HttpModule的新实例

时间:2020-02-20 09:05:45

标签: typescript axios nestjs

我的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

1 个答案:

答案 0 :(得分:1)

在阅读了Dynamic Modulesthis bug report的文档之后,事实证明,在导入中调用register()方法将创建HttpModule的单独实例。

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

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

我不确定这是否是正确的方法,但似乎可行。