如何在Nest.js中注入HttpModule.registerAsync配置的多个HttpService实例?
在Nest.js中注入多个配置不同的HttpService
核心思路
要区分多个预配置的HttpService,关键是给每个HttpModule的配置绑定自定义注入令牌,让服务能通过令牌精准注入对应实例。
实现步骤
1. 定义自定义注入令牌
先创建两个常量作为标识不同HttpService的令牌:
// http-tokens.ts export const FIRST_API_HTTP_SERVICE = Symbol('FIRST_API_HTTP_SERVICE'); export const SECOND_API_HTTP_SERVICE = Symbol('SECOND_API_HTTP_SERVICE');
2. 注册带令牌的HttpModule
在模块中注册HttpModule时,将配置后的HttpService绑定到自定义令牌,并导出这些令牌对应的提供者:
@Module({ imports: [ HttpModule.registerAsync({ useClass: FirstAPIHttpOptions, providers: [ { provide: FIRST_API_HTTP_SERVICE, useExisting: HttpService, }, ], exports: [FIRST_API_HTTP_SERVICE], }), HttpModule.registerAsync({ useClass: SecondAPIHttpOptions, providers: [ { provide: SECOND_API_HTTP_SERVICE, useExisting: HttpService, }, ], exports: [SECOND_API_HTTP_SERVICE], }), ], providers: [GlueLogicService], }) export class AppModule {}
3. 在服务中注入指定的HttpService
在GlueLogicService中,用@Inject()装饰器配合自定义令牌,分别注入两个不同配置的实例:
@Injectable() export class GlueLogicService { constructor( @Inject(FIRST_API_HTTP_SERVICE) private readonly firstApiHttpService: HttpService, @Inject(SECOND_API_HTTP_SERVICE) private readonly secondApiHttpService: HttpService, ) {} // 使用示例 async fetchFirstApiData() { return this.firstApiHttpService.get('/first-api-endpoint').toPromise(); } async fetchSecondApiData() { return this.secondApiHttpService.get('/second-api-endpoint').toPromise(); } }
简化实现方式
也可以直接在HttpModule.registerAsync配置中指定provide字段,省去额外的提供者定义:
@Module({ imports: [ HttpModule.registerAsync({ provide: FIRST_API_HTTP_SERVICE, useClass: FirstAPIHttpOptions, }), HttpModule.registerAsync({ provide: SECOND_API_HTTP_SERVICE, useClass: SecondAPIHttpOptions, }), ], providers: [GlueLogicService], }) export class AppModule {}
注入写法和上述一致,依然通过@Inject(TOKEN)指定目标实例。
内容的提问来源于stack exchange,提问作者Capi Huamani
相关产品推荐
相关产品推荐

