Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs Dependency Injection - Inject service into service

I have a service which I can inject into other components without any issues.

When I try to inject that service into another service I get

Error: Nest can't resolve dependencies of the AService (?). 
Please make sure that the argument BService at index [0] is available in the AService context.

I cannot find any way to inject services into each other. Is this not supported, kind of an anti-pattern.... ?

And if so, how to handle a service with functionality I want to be available in all of my app in several components and services?

Code as follows:

b.module.ts

import { Module } from '@nestjs/common';
import { BService } from './b.service';

@Module({
  imports: [],
  exports: [bService],
  providers: [bService]
})
export class bModule { }

b.service.ts

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

@Injectable()
export class BService {
  someFunc();
}

a.module.ts

import { Module } from '@nestjs/common';
import { SensorsService } from './a.service';
import { SensorsController } from './a.controller';
import { BModule } from '../shared/b.module';

@Module({
  imports: [BModule],
  providers: [AService],
  controllers: [AController],
  exports: []
})
export class AModule { 

}

a.service.ts - which should be able to use b.service

import { Injectable } from '@nestjs/common';
import { BService } from '../shared/b.service';

@Injectable()
export class AService {
  constructor(
    private bService: BService
  ) {}

  someOtherFunc() {}
}
like image 285
FuzzyTemper Avatar asked May 22 '20 10:05

FuzzyTemper


1 Answers

Based on your error, you have AService in an imports array somewhere, which is not something you do in NestJS. To break it down

Error: Nest can't resolve dependencies of the AService (?).

Please make sure that the argument BService at index [0] is available in the AService context.

The first part is showing the Provider that is having difficulties, along with a ? where the unknown dependency is. In this case, AService is the provider that cannot be instantiated and BService is the unknown dependency.

The second part of the error is calling out explicitly the injection token (usually a class name) and the index in the constructor and then in what module context Nest is looking at. You can read that Nest says

in the AService context

Meaning Nest is looking at a module called AService. As I said before, this is something you shouldn't do.

If you are needing the AService in another module, you should add the AService to the AModule's exports array, and add AModule to the new module's imports array.

like image 88
Jay McDoniel Avatar answered Nov 15 '22 04:11

Jay McDoniel