NestJS Troubleshooting: Nest is unable to resolve dependencies required by the ChildService

My project has a class structure set up like this:

Inside the libs/childmodule/src/child.module.ts, I have a ChildModule. It is mapped to @app in the taconfig.json file.

In addition, there is a ParentModule where I am attempting to import the ChildModule. The code structure is as follows:

ChildModule:


import { Module } from '@nestjs/common';
import { ChildService } from './child.service';
import { LoggerModule } from '@app/logger';
import { CommonModule } from '@app/common';
import { SecretsModule } from '@app/secrets';

@Module({
  providers: [ChildService],
  exports: [ChildService],
  imports: [
    LoggerModule,
    CommonModule,
    SecretsModule,
  ],
})
export class ChildModule {}

The ParentModule looks like this:

import { ChildModule } from '@app/child';

@Module({
  imports: [SomeModule, LoggerModule, ChildModule],
  controllers: [ParentController],
  providers: [ParentService],
  exports: [ParentService],
})
export class ParentModule {}

Currently, I have not yet used the ChildService via Dependency Injection (DI).

The error message I am encountering reads:

Error: Nest cannot resolve dependencies of the ChildService (LoggerService, CommonService, ?). Please ensure that the SecretsService at index [2] is available in the ChildModule context.

Possible solutions:
- If SecretsService is a provider, is it included in the current ChildModule?
- If SecretsService is exported from a separate @Module, is that module imported within ChildModule?
  @Module({
    imports: [ /* the Module containing SecretsService */ ]
  })

The way I understand it, if I import a module (such as ChildModule) into the parent module, all the dependencies of ChildModule should be automatically resolved. In other words, I should not have to manually list all of ChildModule's dependencies in the providers of my parent module.

I am at a loss as to what may be missing here.

For further clarification, here is the SecretsModule:

SecretsModule

import { Global, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { SecretsService } from './secrets.service';
import { Module1Module, Module1Service } from '@app/module1';

@Global()
@Module({})
export class SecretsModule {
  static forRoot(some_key) {
    return {
      module: SecretsModule,
      imports: [Module1Module, ConfigModule],
      providers: [
        {
          provide: SecretsService,
          useFactory: async (
            configService: ConfigService,
            service1: Module1Service,
          ) => {
            const secretsService = new SecretsService(
              configService,
              service1,
              some_key,
            );
            await secretsService.init();
            return secretsService;
          },
          inject: [ConfigService, Module1Service],
        },
      ],
      exports: [SecretsService],
    };
  }
}

Answer №1

In the construction of the ChildService, the third parameter is the SecretsService. It is assumed that the SecretsService resides in the SecretsModule. To use the SecretsService within the context of the ChildModule, you must designate the service as an exporter in the SecretsModule. This allows you to utilize the service in any module by importing the relevant module.

To implement these changes:

//secrets.module.ts
@Module({
  imports: [...],
  controllers: [...],
  providers: [...],
  exports: [SecretsService],
})
export class SecretsModule {}

Repeat this process for any similar cases you encounter.


Update:

Because SecretsModule is a dynamic module, you must invoke forRoot in each module where you intend to import SecretModule, as Nest won't be able to import it otherwise.

//child.module.ts
@Module({
  providers: [ChildService],
  exports: [ChildService],
  imports: [
    LoggerModule,
    CommonModule,
    SecretsModule.forRoot(/*since forRoot takes parameter `some_key`, you need to provide it here*/),
  ],
})
export class ChildModule {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include text or a label on my Angular map without using a marker?

I am currently using the agm-map module in my angular project. I want to place a label or text at the center of a polygon on the map without using markers. How can I achieve this functionality in Typescript? I attempted to use the MapLabel Utility for thi ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

What potential drawbacks come with utilizing the OOP approach in both JavaScript and React?

While working on an internal project, I found myself creating a base system and implementing a custom form structure using TypeScript with an OOP approach. class Form extends React.Component {} abstract class FormElement extends React.Component<{valid ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Having trouble initializing useReducer in React paired with TypeScript

I'm currently delving into the world of TypeScript and facing a challenge with setting up the useReducer function. It seems like the solution might be a simple one, so apologies in advance. Below is an excerpt from my App.tsx file: import React, { use ...

Set the styling of a div element in the Angular template when the application is first initialized

I have a question about this specific div element: <div class="relative rounded overflow-clip border w-full" [style.aspect-ratio]="media.value.ratio"> <img fill priority [ngSrc]="media.value.src || ftaLogo" ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

Exploring the power of Prosemirror with NextJS through Tiptap v2

Greetings everyone, I am a newcomer to Stack Overflow and I am reaching out for assistance regarding an issue that has arisen. The problem at hand pertains to the development of the Minimum Viable Product (MVP) for my startup which specializes in creating ...

Is it possible to perform remote file upload using Selenium in TypeScript?

Is there a specific way to manage remote file uploads using selenium-webdriver in typescript? Here is code that functions in javascript for this purpose: import remote from 'selenium-webdriver/remote'; // import * as remote from 'selenium- ...

Encountering a fresh issue after updating to TS version 4.4.3 while accessing properties of the top "Object may be 'null'."

After upgrading my project to TypeScript 4.4.3 from 3.9.9, I encountered a change in the type declarations for the top property. My project utilizes "strictNullChecks": true, in its configuration file tsconfig.json, and is browser-based rather t ...

I'm encountering an issue with my Angular 8 function not running, and I'm unsure of the reason behind it as there are no error messages appearing

Here is a function that I have: Join(movementId: string, movement: Movement, userId: string) { let fetchedUserId: string; let userList = []; fetchedUserId = userId; userList = movement.userList; userList.push(fetchedUserId); movement.userList ...

Issue with Angular Datatable: Table data is only refreshed and updated after manually refreshing the page or performing a new search query

Having trouble updating Angular Datatable after selecting different data? The API response is coming in but the table data is not being updated. Can anyone suggest how to properly destroy and reinitialize the table for the next click? Below is a snippet ...

What is the term for specifying a variable's data type using a set of values instead of a traditional type?

Recently, I stumbled upon some code that introduces a class with specific variables defined in an unconventional manner. export class Foo { id: string = "A regular string" bar: '>' | '<' | '=' | '<=' | ...

Is it possible to retrieve the second computed type in an overloaded method using TypeScript?

Looking for a solution to receive the second calculated type in an overload method using TypeScript type V1 = 'v1'; type V2 = 'v2'; type Versions = V1 | V2; async analyze(test: 'v1', data: number): Promise<void> ...

Utilize mapping for discriminated union type narrowing instead of switch statements

My objective is to utilize an object for rendering a React component based on a data type property. I am exploring ways to avoid utilizing switch cases when narrowing a discriminated union type in TypeScript. The typical method involves using if-else or sw ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

Updating color of an element in SVG and Angular2+ according to the background

In my svg element, I have a text element positioned after two rect elements. <svg id="floor-plan" width="300" height="100"> <rect width="300" height="100" fill="white"/> <rect width="50" height="50" fill="green"/> <text x="10" y="10" ...

The directive for angular digits only may still permit certain characters to be entered

During my exploration of implementing a digits-only directive, I came across a solution similar to my own on the internet: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appOnlyDigits]' ...