Mike O.
Mike O.

Reputation: 1045

How to manually inject dependency in nestjs

In angular we can manually access and inject dependencies using the built in Injector class. By which you can access Injectables and Inject them without actually passing them in the constructor. Basically I want to inject a service to another service without passing it as an arg to the constructor.

This is the angular equivalent Inject a service manually

I wanted to achieve similar thing in nestjs

Note : The service to be injected also has a dependency, so I can't just instantiate it

Upvotes: 7

Views: 8717

Answers (2)

Hồ Thiện Lạc
Hồ Thiện Lạc

Reputation: 99

I think @Inject('token') should work as you expected

import { Injectable, Inject } from '@nestjs/common';

@Injectable()
export class HttpService<T> {
  @Inject('HTTP_OPTIONS')
  private readonly httpClient: T;
}

ref: https://docs.nestjs.com/providers#property-based-injection

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70061

I believe what you're looking for is Nest's ModuleRef class, where you can do something like the following:

@Injectable()
export class CatsService implements OnModuleInit {
  private service: Service;
  constructor(private moduleRef: ModuleRef) {}

  onModuleInit() {
    this.service = this.moduleRef.get(Service);
  }
}

Where Service should actually be the class you are wanting to inject.

Upvotes: 9

Related Questions