【问题标题】:How to set a parametr in the contructor of injection service?如何在注入服务的构造函数中设置参数?
【发布时间】:2021-09-24 09:39:28
【问题描述】:
我有一个服务,我在构造函数中注入另一个带有参数的服务。
主要服务
export class Test1Service {
constructor(
test2Service: Test2Service
) {}
getIndex() {
console.log(111);
}
}
注入服务
@Injectable()
export class Test2Service {
item;
constructor(name) {
if (name === 'blog') {
this.item = 'item1';
} else {
this.item = 'item2';
}
}
}
【问题讨论】:
标签:
dependency-injection
nestjs
【解决方案1】:
这将改变模块中的供应商导入:
@Module({
controllers: [AppController],
providers: [
Test1Service,
{
provide: 'BLOG',
useValue: new Test2Service('blog'),
},
{
provide: 'ANALYTICS',
useValue: new Test2Service('analytics'),
}
],
})
export class AppModule {}
在服务中使用它
@Injectable()
export class Test1Service {
constructor(
@Inject('BLOG') public testBlog: Test2Service,
@Inject('ANALYTICS') public testAnalytics: Test2Service
) {}
getIndex() {
this.testBlog.getIndex()
this.testAnalytics.getIndex()
}
}