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

Edw*_*win 2 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;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Edw*_*win 5

阅读有关动态模块的文档和此错误报告后,发现调用register()导入中的方法会创建一个单独的HttpModule.

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

@Module({
  imports: [
    HttpModule.register({}),
  ],
  // providers and exports
})
Run Code Online (Sandbox Code Playgroud)

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