gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:48:38 25 4
gpt4 key购买 nike

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

最佳答案

阅读 Dynamic Modules 上的文档后和 this bug report事实证明,在导入中调用 register() 方法会创建 HttpModule 的单独实例。

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

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

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

关于typescript - NestJS:每个模块导入 HttpModule 的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60316235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com