将HttpInterceptorsService移至独立库后Nest无法注入HttpService
Nest独立库中HttpService依赖注入失败问题解决
问题背景
原本在同仓库实现的HttpInterceptorsService可正常向Nest HttpService的AxiosRef注册拦截器,导入AppModule的providers后运行无异常。但将该拦截器类迁移至独立仓库构建的库中,导入API项目后出现如下错误:
Nest can't resolve dependencies of the HttpInterceptorsService (?). Please make sure that the argument HttpService at index [0] is available in the AppModule context.
同仓库时的服务代码
import { Injectable } from '@nestjs/common' import { HttpService } from '@nestjs/axios' @Injectable() export class HttpInterceptorsService { constructor(private readonly httpService: HttpService) { this.httpService.axiosRef.interceptors.request.use((config) => { console.log('Interceptor is running...') return config }) } }
同仓库时的AppModule代码
import { Module } from '@nestjs/common'; import { HttpModule } from '@nestjs/axios'; import { HttpInterceptorsService } from './http-interceptors'; @Module({ imports: [HttpModule], providers: [HttpInterceptorsService], }) export class AppModule {}
迁移至独立库后的AppModule代码
import { Module } from '@nestjs/common'; import { HttpModule } from '@nestjs/axios'; import { HttpInterceptorsService } from 'http-interceptors-lib'; @Module({ imports: [HttpModule], providers: [HttpInterceptorsService], }) export class AppModule {}
问题原因
- 独立库构建时可能将
@nestjs/axios、@nestjs/common等依赖打包进库文件,导致主项目与库中的HttpService实例不统一,Nest依赖注入系统无法识别。 - 库未正确声明peer依赖,也未通过模块管理依赖注入上下文,导致主模块无法将HttpService实例传递给库中的服务。
解决方案
1. 配置库的peerDependencies
在独立库的package.json中,将相关Nest依赖声明为peer依赖,避免重复打包:
{ "peerDependencies": { "@nestjs/common": "^10.0.0", "@nestjs/axios": "^3.0.0" } }
2. 在独立库中创建模块封装服务
不要直接导出服务,而是创建模块管理依赖与服务:
// 独立库中的HttpInterceptorsModule.ts import { Module } from '@nestjs/common'; import { HttpModule } from '@nestjs/axios'; import { HttpInterceptorsService } from './http-interceptors.service'; @Module({ imports: [HttpModule], providers: [HttpInterceptorsService], exports: [HttpInterceptorsService] // 导出服务供主项目调用 }) export class HttpInterceptorsModule {}
3. 主项目导入库的模块
修改主项目AppModule,导入库的模块而非直接注册服务:
import { Module } from '@nestjs/common'; import { HttpInterceptorsModule } from 'http-interceptors-lib'; @Module({ imports: [HttpInterceptorsModule], }) export class AppModule {}
通过以上步骤,Nest依赖注入系统会通过库模块正确获取HttpService实例,解决依赖注入失败问题。
内容的提问来源于stack exchange,提问作者Carlos André
相关产品推荐
相关产品推荐

