I have a CheckModule
which accepts configuration in the forRoot
method using a constant CHECK_OPTIONS
:
@Module({})
export class CheckModule {
static forRoot(options?: CheckOptions): DynamicModule {
return {
module: CheckModule,
providers: [
{
provide: CHECK_OPTIONS,
useValue: options,
},
CheckService,
],
exports: [CheckService],
};
}
}
My CheckService
uses the options:
@Injectable()
export class CheckService {
...
constructor(@Inject(CHECK_OPTIONS) options: CheckOptions) {}
...
Whenever I debug the application, everything is working fine. But, once I build for production and serve it on Heroku I get an error.
# Production build
nx build $PROJECT_NAME --prod
# Serving the app
node dist/apps/worker/main.js
I get an error:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the CheckService (?). Please make sure that the argument CHECK_OPTIONS at index [0] is available in the CheckModule context.
Am I missing something here? I'm kind of clueless...
CodePudding user response:
Seems like your module needs to be global.
Try adding @Global()
decorator before @Module({})
.
CodePudding user response:
In my app.module
I imported the CheckModule as:
imports: [
CheckModule.forRoot(),
...
]
This method had an optional parameter for CheckOptions
:
forRoot(options?: CheckOptions) { ... }
However my CheckService expects a CHECK_OPTIONS
which is not optional. This is what caused the error. Correctly marking this InjectionToken as @Optional()
resolved this issue.
So, I've changed the code from:
constructor(@Inject(CHECK_OPTIONS) options?: CheckOptions) {}
To:
constructor(@Optional() @Inject(CHECK_OPTIONS) options?: CheckOptions) {}
^^^^^^^^^^^
See https://docs.nestjs.com/providers#optional-providers for more information about the @Optional()
decorator.