7

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

Mike O.
  • 905
  • 1
  • 8
  • 13

2 Answers2

7

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.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • 2
    Just a remark, that if you want to resolve a dependency from other than current module, you need to also pass { strict: false } as 2nd parameter. – Sielu Feb 11 '21 at 11:39
0

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