V
V
Vladimir Golub2021-07-15 16:29:33
Node.js
Vladimir Golub, 2021-07-15 16:29:33

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);
    }
}

There is a second service:
@Injectable()
export class Test2Service {
    item;

    constructor(name) {
        if (name === 'blog') {
            this.item = 'item1';
        } else {
            this.item = 'item2';
        }
    }
}

How to pass parameter to constructor when importing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Golub, 2021-07-15
@RazerVG

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 question

Ask a Question

731 491 924 answers to any question