Answer the question
In order to leave comments, you need to log in
How to pass parameter to class constructor when adding it via Dependency Injection (NestJS)?
There is one service:
@Injectable()
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';
}
}
}
Answer the question
In order to leave comments, you need to log in
It works
@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()
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question