Integrate a service component into another service component by utilizing module exports

After diving into the nestjs docs and exploring hierarchical injection, I found myself struggling to properly implement it within my project. Currently, I have two crucial modules at play.

AuthModule is responsible for importing the UserModule, which contains a service utilized by other modules where it functions flawlessly.

auth.module.ts

import * as passport from 'passport';
import {
  Module,
  NestModule,
  MiddlewaresConsumer,
  RequestMethod,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import {JwtStrategy} from './jwt.straegy';

import {UserModule} from '../shared/user/user.module';

@Module({
  imports: [UserModule],
  components: [AuthService, JwtStrategy],
  exports: [AuthService]
})
export class AuthModule implements NestModule {
  public configure(consumer: MiddlewaresConsumer) {
    consumer
      .apply(passport.authenticate('jwt', { session: false }))
      .forRoutes({ path: '/cats', method: RequestMethod.ALL });
  }
}

user.module.ts

import {Module} from '@nestjs/common';
import {MongooseModule} from '@nestjs/mongoose';
import {UserSchema} from '../../schema/user.schema';
import {UserService} from './user.service';

@Module({
  imports: [
    MongooseModule.forFeature([{ name: 'UserInterface', schema: UserSchema }])
  ],
  components: [UserService],
  exports: [UserService]
})
export class UserModule {}

The issue arises when UserService is injected into AuthService within the nestjs framework, resulting in an error notification. Strangely enough, UserService operates smoothly in other modules.

Error: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.

auth.service.ts

import * as jwt from 'jsonwebtoken';
import { Component } from '@nestjs/common';
import {UserService} from '../shared/user/user.service';

@Component()
export class AuthService {

  constructor(private readonly userService: UserService) {}

  async createToken(username) {
    const expiresIn = 60 * 60, secretOrKey = 'i am fake!';
    const user = {username};
    const token = jwt.sign(user, secretOrKey, {expiresIn});
    return {
      expires_in: expiresIn,
      access_token: token
    };
  }

  async validateUser(signedUser): Promise<boolean> {
    return !!(await this.userService.findByUsername(signedUser.username));
  }
}

Answer №1

It's quite peculiar, I have a similar code that is functioning well. One thing I observed is that you may be using the authService in another module? If that's the case, you might need to re-export the usersModule in the authModule so that it can be accessed within your current scope:

In authModule:

exports: [UserModule, AuthService]

(I couldn't provide a full example as Stack Overflow seems to be having issues with displaying code blocks)

If this adjustment resolves the issue, it's possible that you've added the authService to another module without importing the entire authModule. If you could share a GitHub repository containing all the code, it would make troubleshooting easier.

Remember, the authService should now be considered part of the authModule and not directly added to any other modules. It should only be accessed through the "import" array. If this doesn't align with your setup, sharing the full code on GitHub could facilitate finding a solution.

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

Guide on implementing conditional return types in React Query

In my approach, I have a method that dynamically uses either useQuery or useMutation based on the HTTP method passed as a prop. However, the return type of this method contains 'QueryObserverRefetchErrorResult<any, Error>', which lacks meth ...

Typescript encounters difficulty locating the designated interface

Within my Aurelia View-Model, I am working on a Typescript file that contains the following structure: import {Chart} from './chart'; interface IMargin { top: number, right: number, bottom: number, left: number } export class App{ cha ...

The issue encountered is a Type Error, as the function crypto.randomUUID() is

Everything is running smoothly with my Next.js app on http://localhost:3000/. To enhance the experience, I made an update to my hosts file. 127.0.0.1 customdomain.local After connecting to http://customdomain.local:3000/, I encountered an error in my cli ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : https://i.sstatic.net/myJAf.png On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Ri ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

Angular 2 failing to recognize service variable changes initiated from component

Hello there, I'm currently facing a challenge with updating my component to reflect the correct value of a service variable whenever it changes. Here's what I have so far: Snippet from Component1 HTML {{icons | json}} Component1 Code icons: ...

Using MobX to alter observed observable values outside of actions is not permitted in combination with Ant Design components

When trying to upload files to the server and receive a response, I encountered an issue. If I override the onChange property of the Upload component (from antd), mobx starts throwing errors and the file uploading process gets stuck in the 'uploading& ...

What is causing my function to execute twice in all of my components?

One issue I am facing is that I have created three different components with routing. However, when I open these components, they seem to loop twice every time. What could be causing this behavior and how can I resolve it? For instance, in one of the comp ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

Is there a way to retrieve the number of swipe up interactions from Instagram story insights using the graph API

Is there a way to retrieve the swipe up count displayed in Instagram insights? Since Facebook does not provide this data through their Graph API, how can I access it? I have already tried scraping without success and I am looking for a solution using eith ...

What is the best way to refresh a personalized form element using Angular?

I have developed a custom form control with validation that utilizes a standalone FormControl to manage the value and perform certain validations. Is there a method in Angular to reset the inner FormControl when the control is being reset from another For ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

Accessing the return value from an Angular subscription and storing it in

How can I use the value from a subscription to set the property for returning date and time? Component ngOnInit() { this.resetForm(); let defaultWIPEndTime = this.service.getDefaultWIPEndTime().subscribe(res => {}); console.log(defaultW ...

Karma Unit test: Issue with accessing the 'length' property of an undefined value has been encountered

While running karma unit tests, I encountered a similar issue and here is what I found: One of my unit tests was writing data to a json file, resulting in the following error: ERROR in TypeError: Cannot read property 'length' of undefined a ...

The state data is not being properly updated and is getting duplicated

While developing a loop to parse my API data, I encountered an issue where the values obtained were not being captured properly for dynamically loading corresponding components based on their characteristics. The problem arose after implementing useState() ...

What is the best way to send props to a child component in JSX with TypeScript?

While passing props to the child, I encountered an error message stating "Property 'isClicked' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes". I defined "isClicked?: boolean" in my code. What additional steps sho ...

The issue with the react-diagram stemmed from a conflict with @emotion/core

During the installation of react-diagrams by projectStorm, I encountered some errors which are shown in the following image: errorImg Despite attempting to downgrade the version of '@emotion/core' to ^10.0.0, the issue persisted. Here is a view ...

typescriptUsing redux: prevent parent component from accessing redux props

I'm currently using redux and typescript in my webapp project. What's the best approach for defining props in a component that receives redux-actions through @connect, as well as props from its parent? // mychild.tsx export namespace MyChildCom ...