The dependencies for the AuthService cannot be resolved by Nest. The UsersService at index [0] is accessible within the AuthModule context

After struggling with this error for almost 48 hours, I still haven't been able to find a solution. Can someone please help me troubleshoot this issue? I attempted to use Circular dependency forward referencing within the module, but it was unsuccessful.

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

Potential solutions:
- Is AuthModule a valid NestJS module?
- If UsersService is a provider, is it part of the current AuthModule?
- If UsersService is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing UsersService */ ]
  })

    at Injector.lookupComponentInParentModules (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:244:19)   
    at Injector.resolveComponentInstance (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:197:33)
    at resolveParam (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:117:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:132:27)
    at Injector.loadInstance (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:58:13)
    at Injector.loadProvider (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:85:9)
    at C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\instance-loader.js:49:13
    at async Promise.all (index 3)
    at InstanceLoader.createInstancesOfProviders (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\instance-loader.js:48:9)

users.service.ts

@Injectable()
export class UsersService {
  constructor(

  @InjectRepository(UserEntity) private repo: Repository<UserEntity>) {}
  
  async create(createUserDto: CreateUserDto):Promise<UserEntity> {
    const user = new UserEntity();
    user.firstname = createUserDto.firstname;
    user.lastname = createUserDto.lastname;
    user.email = createUserDto.email;
    
    return await this.repo.save(user) 

  }

  async findAll():Promise<UserEntity[]> {
    return await this.repo.find();
  }

  async findOne(id: number):Promise<UserEntity> {
    return await this.repo.findOne({
      select:['id','firstname','lastname',"email"],
      where:{id}
    });
  }

users.module.ts

@Module({
  imports:[TypeOrmModule.forFeature([UserEntity]),PassportModule,forwardRef(() =>AuthModule)],
  controllers: [UsersController],
  providers: [UsersService],
  exports:[UsersService]
})
export class UsersModule {}

users.entity.ts

@Entity()
export class UserEntity {
    @PrimaryGeneratedColumn()
    id: number;
   
    @Column()
    firstname: string;

    @Column()
    lastname: string;

    @Column()
    email:string;
    
   
}

auth.service.ts

@Injectable()
export class AuthService {
    constructor(@Inject('UsersService') private  userService:UsersService){}

    async validateUser(id:number,password:string){
        const user = await this.userService.findOne(id)
        if(user.id === id){
            return user
        }
        return null
    }
}

auth.module.ts

@Module({
  imports:[forwardRef(() => UsersModule)],
  providers: [AuthService,UsersService],
  exports:[AuthService]
})
export class AuthModule {}

This is my folder structure: enter image description here

Answer №1

When you bring in a module, you're essentially accessing the resources it provides. It doesn't make sense to include UsersService within AuthModule when you already have UsersModule imported.

If you're using nestjs version 8 or above, utilizing a string as a token for class-based providers will not function correctly. Remove the @Inject('UsersService') and replace it with

@Inject(forwardRef(() => UserService))
.

The organization of your folders is not crucial, but be cautious about having multiple barrel files that could lead to circular imports. You can find more information on this topic here: Strategies to Prevent Circular Dependencies in NestJS

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

The issue with binding arises when attempting to bind in nested elements within an ng-repeat loop

Here is the code snippet I am working with: <div class="list-group"> <a href="#" class="list-group-item" ng-repeat="user in users"> <h4 class="list-group-item-heading">{{user.FirstName}} {{user.LastName}}</h4> <p class=" ...

What is the best way to automatically collapse an open navbar in Bootstrap 3 when it is clicked outside of the navbar element?

Is there a way to automatically close a collapsed navbar when clicking outside of the navbar itself? Currently, the only option is to toggle it open or closed using the navbar-toggle button. To see an example and code, click here. I have attempted the fo ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

Ways to conceal a section of columns within a table

I am working on a table that combines 2 separate tables. <div> <div> <table> <colgroup> <col style="width:95px" /> <col style="width:95px" /> ...

typescript - transforming text into numerical values

newbalance = (Number(this.balance)) + (Number(this.pastAmount)); The result for my newbalance calculation is coming back as undefined, even though this.balance is 34 and this.pastAmount is 23. I've set this up in the controller and I'm trying t ...

Instructions for deleting a class from the body with jQuery while incorporating AngularJS

When using jQuery $(document).ready(function() { $("#pid1").removeClass("login_page"); }); HTML <body class="login_page" id="pid1" ng-app="myApp" ng-controller="myCtrl"> On the main page, a class is removed, but on the login page I want to ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

Show an HTML image encoded in base64 from its origin

Is there a way to embed a base64 image in HTML without having to paste the entire code directly into the file? I'm looking for a more efficient method. For example: <div> <p>Image sourced from an online repository</p> <img src=" ...

Attempting to grasp the concept of Typescript generics

I have a function defined as follows: interface ExtraModels extends Model { unknown: string } const write = async (data: ExtraModels[]) => { console.log(data[0].unknown) } This function is currently working. However, I want to modify it to: cons ...

Fresh Regular Expression created from a readable string

I can't figure out why rg = new RegExp(`/${a}.*${b}/`) isn't functioning properly here, while rg = /\(.*\)/ is working fine. let a = '\('; let b = '\)'; let rg; //rg = new RegExp(`/${a}.*${b}/`); // doesn&a ...

Engage with Vue.js and traditional JavaScript (plain) in your projects

Exploring the integration of Vue with regular JavaScript has presented a challenge. While some solutions online propose moving all functions to a Vue component, this approach proves impractical for complex or large functions. The task now is finding a way ...

Create a fresh type by dynamically adjusting/filtering its attributes

Suppose we have a type defined as follows: type PromiseFunc = () => Promise<unknown>; type A = { key1: string; key2: string; key3: PromiseFunc; key4: string; key5: PromiseFunc; key6: SomeOtherType1[]; key7: SomeOtherType2[]; key8: ...

Update of input not available

Does anyone know how to effectively transfer data from one page to another programmatically? I'm facing an issue where updating an input field doesn't work unless I manually edit it afterwards. Is there a better way to achieve this? Another prob ...

Exploring potentials in OpenLayers by filtering characteristics

Is there a way to filter map features based on their properties? For example, if I have the following property in the geojson: ... "properties": { "Start": 10 } ... How can I make it so that only features w ...

Guide on checking the presence of an error message post button click using react testing library

Hey there, I'm currently in the process of testing my react app's behavior using @testing-library/react version: 11.2.3 @testing-library/jest-dom version 5.11.9 I'm aiming to observe an error message that appears after a button is clicked. ...

Invoking the callback function within the containing scope in Typescript

I am facing an issue with my Angular component where I have a class that includes common services and functions. While passing some functions as callbacks, the scope is getting lost during execution. Let me demonstrate the problem through the code below: @ ...

when utilizing the map operator in Rxjs

After diving into rxjs and Angular recently, I attempted to create an API for accessing a web service. I started by defining the following type: export type Banner = { targetId: number; url: string; imageUrl: string; ...

HTML drop-down menu not descending as expected

Recently, I've encountered a simple issue with adding a dropdown menu to the navbar to enable sorting options by price, category, rating, etc. Unfortunately, the dropdown functionality is not working as expected. Despite my efforts to troubleshoot by ...

Utilizing React Native Camera Kit allows for the seamless and continuous scanning of QR codes, offering multiple callbacks when a code is

Attempting to integrate a QR code scanner into my project using react native. Utilizing the plugin react-native-camera-kit, which supports both QR and Bar code scanning. However, I am facing an issue where the scanner continuously scans the code and trig ...

Include additional information beyond just the user's name, profile picture, and identification number in the NextAuth session

In my Next.js project, I have successfully integrated next-auth and now have access to a JWT token and session object: export const { signIn, signOut, auth } = NextAuth({ ...authConfig, providers: [ CredentialsProvider({ async authorize(crede ...