Guide: Implementing service utilization within a controller using Express and Typescript

This specific piece of TypeScript code is causing me some trouble. I'm attempting to utilize a service to retrieve data from a database, but unfortunately, I keep encountering the following error message:

Cannot read property 'populationService' of undefined
.

Controller.ts =>

import { PopulationService } from "../services/population.service";

export class PopulationController implements IController {
public path: string = "/population";
public router = Router();

private populationService: PopulationService = new PopulationService();

constructor() {
    this.initializeRoutes();
}

private initializeRoutes() {
    this.router.get(`${this.path}/getEmployer`, this.getEmployer);
}

private async getEmployer(request: Request, response: Response, next: NextFunction) {
    try {
        let result = await this.populationService.getEmployerFromService();
        return response.status(200).send(result);
    }
    catch (error) {
        next(error);
    }
}
}

Service.ts =>

import { pool } from "../../config/database";

export class PopulationService {

    public async getEmployerFromService(): Promise<any> {
        let sql = `SELECT * FROM population;`;
        let result = await pool.query(sql);
        return result.rows;
    }
}

What could possibly be the issue here? Despite using the new keyword to instantiate the service in the controller, I am still facing this persistent error.

Answer №1

When you pass `this.getEmployer` as a regular function, the connection to `this` is disconnected. To resolve this issue, there are several solutions available but one approach I find effective is to do it within your class constructor:

constructor() {
  this.getEmployer = this.getEmployer.bind(this);
  this.initializeRoutes();
}

Answer №2

One alternative is to convert it into an arrow function.

private fetchEmployer = async (req: Request, res: Response, next: NextFunction) => {
        let result = await this.populationService.fetchEmployerData();
        return res.status(200).send(result);
 }

I'm not entirely sure if this is the optimal fix. If you have a better suggestion, feel free to share it.

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 reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

Tips for circumventing if statements in TypeScript-ReactJS?

I currently have various action checks in place to perform different functions. Essentially, I am using if and else conditions to determine the action type and execute the corresponding functionality as shown below: public onMessage = (messageEvent) => ...

Simulated FTP Connection Setup and Error Event in Node.js using Typescript

In my Node-Typescript-Express application, I am utilizing the FTP library to connect and retrieve files from a designated location. As part of creating unit tests, I am focusing on mocking the library to ensure coverage for code handling Ready and Error ev ...

What is the syntax for declaring a list of JSON objects in TypeScript?

I've been attempting to implement something similar to the following: interface IUser { addresses: JSON = []; } Unfortunately, it doesn't seem to be working! I'm looking to store a list of nested JSON objects inside the addresses field, ...

Passing data from ModalService to a component

Currently, I am attempting to utilize the ngx-bootstrap-modal in order to transfer data from a modal service to a modal component. While reviewing the examples, it is suggested to use the following code: this.modalService.show(ModalContentComponent, {init ...

Issue with vue-class-component: encountering TS2339 error when trying to call a method within

My vuejs application is being built using vue-cli-service. After a successful build, I encountered TS2339 errors in my webstorm IDE: Test.vue: <template> <div>{{method()}}</div> </template> <script lang="ts"> impor ...

Obtain the index of a selected option in a Select Tag using Node.js/Express

When you make a POST request with a form in Node.js/Express For example: <select name="selectname"> <option value="value1">Value 1</option> <option value="value2" selected>Value 2</option> <option value="value3"> ...

Incorporate relationships while inserting data using Sequelize

vegetable.js ... var Vegetable = sequelize.define('Vegetable', { recipeId: { allowNull: false, ... }, name: { ... }, }); Vegetable.association = models => { Vegetable.belongsTo(models.Recipe); }; ... recipe.js ... var Recipe = sequeliz ...

Combining Firebase analytics with an Ionic 3 application using the Ionic Native plugin

I placed the GoogleService-Info.plist file at the root of the app folder, not in the platforms/ios/ directory. When I tried to build the app in Xcode, an error occurred in the following file: FirebaseAnalyticsPlugin.m: [FIROptions defaultOptions].deepLin ...

Switching a material-ui input control instead of a textfield for materials-ui-datepicker: the ultimate guide

Within my React application (v16.3), I am utilizing the DatePicker component from the material-ui-pickers library to render date-picker controls. This particular component renders a Material-UI TextField. However, I am interested in modifying it to only di ...

When using node.js with express, the req.on('end') event is triggered, but the req.on('data') event does not fire

When using body parser, you have the option of either: application/x-www-form-urlencoded body parser or json body parser Both options yield the same results. This is how the API is being called: $.ajax({ type:'post', url:'/ ...

Express.js integration with 2Hire Webhook URL is not functioning properly following the migration from Fastify

After switching from a Fastify application to Express.js to handle 2Hire webhooks, I am facing an issue with the webhook URL not triggering as expected. For reference, here are the 2Hire webhook documentation links: 2Hire Webhooks Subscription API Doc: ...

Transforming the header of a table in a CSV file into a schema field

My task is to create a schema for a CSV file using Mongoose, but upon inspecting the file, I discovered it contains nearly a hundred fields or columns. While I am familiar with defining schemas in Mongoose for files with only a few fields, I am unsure ho ...

A Bluebird promise was generated within a NodeJS handler function, however it was not properly returned from the function

Below is the nodejs code for an express middleware function: Middleware.is_authenticated = function(req, res, next) { if(req.system_session == undefined || req.system_session.login_status == false) return res.status(401).send({errors: true, error: &ap ...

Node.js: App crashed, standing by for file changes to initiate restart

While I was in the middle of a nodejs course on Udemy, I encountered an issue where the code suddenly started breaking and throwing errors. Even after attempting to replicate the instructor's code, the problem persisted. I sought guidance from this a ...

Vue.js is known to issue a series of alerts, one of which includes: "Invalid prop: type check failed for prop 'items'. Expected Array, received String with value ''.”

I currently have my front-end set up using vue-cli and the backend utilizing express. The processing time for fetching data from the backend is 1.7 seconds, but when I make the request under the mounted() lifecycle hook in Vue, I receive warnings because V ...

"The value of res.text is not defined for this SuperAgent request

Recently, I decided to try out a TDD approach using Mocha and SuperAgent. However, I encountered a problem when the res.text from SuperAgent turned out to be undefined. Check out the test below: it('should return 2 when the url is /add/1/1', fu ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

Expanding Classes through Index signatories

My attempt at creating an abstract class is not going as smoothly as I hoped. I suspect my limited knowledge of TypeScript is the primary issue, even though this seems like a common scenario. The abstract class I'm working on is called Program. It co ...

Ways to fake an interface using Jest without needing to instantiate it

While Kotlin supports this, I haven't been able to find a way to achieve the same in Jest. My problem arises from having intricate interfaces and arrays of these interfaces where specifying all attribute values is not ideal. Here's an example of ...