An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature module controller:

[RpcExceptionsHandler] Cannot read property 'get_users' of undefined 
TypeError: Cannot read property 'get_users' of undefined
    at UserController.get (/usr/src/app/dist/user/controller/user.controller.js:23:33)
    at /usr/src/app/node_modules/@nestjs/microservices/context/rpc-context-creator.js:44:33
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async /usr/src/app/node_modules/@nestjs/microservices/context/rpc-proxy.js:11:32
    at async ServerTCP.handleMessage (/usr/src/app/node_modules/@nestjs/microservices/server/server-tcp.js:55:54)

Below is a snippet from my user.controller.ts file:

import { Logger } from '@nestjs/common';
import { UserI } from '../models/user.interface';
import { UserService } from '../service/user.service';
import { MessagePattern } from '@nestjs/microservices';

export class UserController {

    private logger = new Logger('AppController');
    constructor(private readonly userService: UserService) {}

    @MessagePattern('add_user')
    async add(user: UserI) {
        return this.userService.add(user);
    }

    @MessagePattern('get_user')
    async get() {
        return this.userService.get_users();
    }
}

Extract from user.service.ts:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { from } from 'rxjs';
import { Repository } from 'typeorm';
import { UserEntity } from '../models/user.entity';
import { UserI } from '../models/user.interface';

@Injectable()
export class UserService {

    
    constructor(
        @InjectRepository(UserEntity)
        private userRepository: Repository<UserEntity>
    ) {}

    add(user: UserI) {
        return this.userRepository.save(user);
    }

    get_users() {
        return this.userRepository.find();
    }
}

Snippet from user.module.ts:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserController } from './controller/user.controller';
import { UserEntity } from './models/user.entity';
import { UserService } from './service/user.service';


@Module({
    imports:[
        TypeOrmModule.forFeature([UserEntity])
    ],
    providers: [UserService],
    controllers: [UserController]
})
export class UserModule {}

app.module.ts setup:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { UserModule } from './user/user.module';

@Module({
  imports: [
    ConfigModule.forRoot({isGlobal:true}),
    TypeOrmModule.forRoot({
      type: 'postgres',
      url: process.env.DATABASE_URL,
      autoLoadEntities: true,
      synchronize: true
    }),
    UserModule
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Answer №1

Make sure to designate UserController as a controller in order to inject dependencies into it. Simply include the @Controller() decorator within your UserController class. Visit this link for more information.

Answer №2

It appears that the UserController is currently being recognized from the AppModule. To avoid any conflicts with metadata, it is recommended to centralize your providers and controllers in a single module file. In this case, consider removing the UserController from the AppModule and confine it solely to the UserModule. This adjustment should resolve the issue you are encountering.

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

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

The text inside the Mapbox GL popup cannot be highlighted or copied

I'm encountering an issue where the text in my popups is unselectable. Even though I can close the popups through various methods, such as clicking on them, the pointer remains as a hand icon when hovering over the text and doesn't change to the ...

Output in Typescript for the chosen option

A message can be sent based on the user's choice of either Now or Later. If the user selects Now, the message will be sent immediately. If Later is chosen, a date format option needs to be created for setting a future date. <label for=""& ...

Toggle visibility of an Angular 4 component based on the current route

Hello there, I'm facing an issue and not sure if it's possible to resolve. Essentially, I am looking to display a component only when the route matches a certain condition, and hide another component when the route matches a different condition. ...

Performing multiple asynchronous tasks using RxJS by running Array.prototype.map in parallel batches or queues

Imagine having an array of variables, such as: [Sasha, Misha, Caitlyn, ...String] (string[]) with a sizable length of about 10k elements. If you want to run an asynchronous parallel task with these elements, but not all at once like Promise.all, rather in ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

Leveraging Ionic 2 with Moment JS for Enhanced TimeZones

I am currently working on integrating moment.js with typescript. I have executed the following commands: npm install moment-timezone --save npm install @types/moment @types/moment-timezone --save However, when I use the formattime function, it appears th ...

Loading an external javascript file dynamically within an Angular component

Currently, I'm in the process of developing an Angular application with Angular 4 and CLI. One of my challenges is integrating the SkyScanner search widget into a specific component. For reference, you can check out this Skyscanner Widget Example. T ...

Ensuring that the app closes completely before launching a new instance with webpack hot module reload

My nest.js application is utilizing webpack hot module reload (hmr), but I am encountering an issue where the reload does not allow the old instance to fully close (including the database connection and telegram bot) before launching a new instance. This c ...

Showing the Enum name rather than the value in an Angular HTML template for a bound Typescript Interface

After retrieving an array of objects with various properties from a .NET Controller, I am utilizing the following Typescript code: import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Co ...

Facing issues with the template URL not functioning properly during the migration from Angular 1.5 to Angular 6

I am currently in the process of migrating an Angular 1.5 project to Angular 6, but I've encountered an issue with the templateUrl not working in the Angular 1.5 component. The packages I am using are: Angular CLI 6.0.8 TypeScript 2.7.2 Angular 6.0.7 ...

Is it possible to verify or authenticate the properties received directly from the associated type or interface?

Looking for a more efficient way to handle validation in my component that takes an array of tabs and children as props. I would like to check if the children provided are the same length as the tabs array directly from the type declaration or any cleaner ...

Is it possible to use Date as a key in a Typescript Map?

Within my application, I have a requirement for mapping objects according to specific dates. Given that typescript provides both the Map and Date objects, I initially assumed this task would be straightforward. let map: Map<Date, MyObject> = new M ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

Retrieve input from text field and showcase in angular 6 with material design components

Take a look at the output image . In the code below, I am displaying the contents of the messages array. How can I achieve the same functionality with a text box and button in an Angular environment? <mat-card class="example-card"> <mat-car ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...

Guide to resolving the issue of error Type 'void[] | undefined' cannot be assigned to type 'ReactNode'

I am attempting to map the data Array but I am encountering an error: Type 'void[] | undefined' is not assignable to type 'ReactNode'. Can someone please assist me in identifying what I am doing wrong here? Below is the code snippet: i ...

Navigating session discrepancies: Combining various social media platforms using Next.js and NextAuth

Recently, I ran into a problem where, upon logging in with Google, I found myself needing access tokens for Twitter and LinkedIn to send out API requests. The issue came about when NextAuth modified my session data to be from either Twitter or LinkedIn ins ...

Issue encountered while iterating over an array using NgFor

I am currently facing an issue while attempting to create a table for viewing certificates in an account using Angular. The error I am encountering is as follows: ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...