You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS模块调用其他模块方法:自定义Axios实例依赖注入问题

问题描述

我正尝试构建一个可为不同模块创建不同Axios实例的系统,但目前无法为服务配置自定义baseURL。尝试使用useFactory实现时,axiosService被解析为undefined。

相关代码

webhook.module.ts

@Module({
  imports: [AxiosModule],
  providers: [
    {
      provide: 'WebhookClient',
      useFactory: (axiosService: AxiosService) => {
        console.log(axiosService); // undefined
        return axiosService.create('http://apiurl.com/api');
      },
    },
  ],
})
export class WebhookModule {}

axios.module.ts

export const AXIOS_INSTANCE_TOKEN = 'AXIOS_INSTANCE_TOKEN';

@Module({
  providers: [AxiosService, { provide: AXIOS_INSTANCE_TOKEN, useValue: axios }],
  exports: [AxiosService],
})
export class AxiosModule {}

axios.service.ts

@Injectable()
export class AxiosService extends HttpService {
  async create(url: string) {
    return axios.create({
      baseURL: url,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  }
}
解决方法

问题核心是useFactory未声明依赖注入目标。NestJS中使用useFactory时,必须通过inject数组明确指定要注入的提供者,否则容器无法解析对应的依赖实例。

修改webhook.module.ts中的提供者配置,添加inject数组:

@Module({
  imports: [AxiosModule],
  providers: [
    {
      provide: 'WebhookClient',
      useFactory: (axiosService: AxiosService) => {
        return axiosService.create('http://apiurl.com/api');
      },
      inject: [AxiosService], // 新增此行,指定要注入的服务
    },
  ],
})
export class WebhookModule {}

另外注意,你的AxiosService.create方法是异步的(带async关键字),所以useFactory也需要对应改成异步函数:

useFactory: async (axiosService: AxiosService) => {
  return await axiosService.create('http://apiurl.com/api');
},

如果不需要异步逻辑,也可以直接把create方法改成同步:

// 同步版本的create方法
create(url: string) {
  return axios.create({
    baseURL: url,
    headers: {
      'Content-Type': 'application/json',
    },
  });
}

内容的提问来源于stack exchange,提问作者Andronik Nazaryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 15:52:11