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() {}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With