Accessing attributes declared in the constructor from within class methods is not possible

I am encountering an issue with my HomeController and its index method. I have declared a variable called `this.data` in the constructor, but when I try to access it within the index method, I get the following error message:

TypeError: Cannot read property 'data' of undefined

Here is my implementation of the HomeController:

import Controller from "./../../vendor/controller";
import * as express from "express";
import hException from "./../helper/exception.helper";

class HomeController extends Controller {
    data:object
    constructor(){
        super()
        this.data = {
            tes: 'tes'
        }
    }
    async index(request:express.Request, response:express.Response, next:express.NextFunction):Promise<any>{
        try {
            let template =  'home/index';
            //next to viewer
            response.render(template, { layout: 'dashboard', data: this.data});
        } catch (error) {
            next(new hException(error))
        }
    }
}

export default HomeController

The Routes file that invokes the HomeController:

import * as express from "express";
import Controller from "./../../controller/home.controller";

import { Jwt as MJwt } from "./../../middleware/auth.middleware";

class Routes {
    private router:express.Router = express.Router()
    private path:string = '/'
    private controller:Controller
    private MJwt = new MJwt()
    constructor() {
        this.controller = new Controller;
        this.run()
    }

    public run(){
        this.router.route(this.path)
            .get(
                this.controller.index
            );
    }
}

export default Routes

Answer №1

After declaring the method of HomeController using an arrow function, the problem was successfully solved. More information can be found in this link. Alternatively, the issue can also be resolved by utilizing binding functions as explained in this link.

The solution was implemented using arrow functions.

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

rely on a fresh event starting at one

Despite my limited knowledge in javascript, I managed to create a simple js calendar that I am quite proud of. However, I have been facing a challenge for the past few days. You can view my calendar here: https://jsfiddle.net/ck3nsemz/ The issue I'm ...

Retrieving documents in Mongoose by searching for nested object IDs will return the complete document

This is the structure of my document: { "_id": "590dc8b17e52f139648b9b94", "parent": [ { "_id": "590dc8b17e52f139648b9b95", "child": [ { "_id": "590dc8b17e52f139648b9b8f" }, { ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...

Error encountered in NodeJS after refreshing the node server

I am currently in the process of developing a web application using Node.js, Express framework, and EJS templates. Below is the code snippet for my server setup: const express = require('express'); const app = express(); const PORT = process.en ...

What steps can I take to resolve the issue of a Promise that remains in a

Currently, I am working on implementing a protected route feature in React. My goal is to modify the result variable so that it returns a boolean value instead of a promise without converting the ProtectedRoute function into an async function: import Reac ...

ESLint encountering a "Module path unresolved" issue in conjunction with SAM Serverless Monorepo

In the process of developing a basic Hello World function for AWS Lambda/APIGateway, I aim to integrate ESLint and Typescript features. Typically, when working with Typescript and ESlint, inclusion of the eslint-plugin-import package and specifying the ext ...

The challenge of extending a TypeScript generic to accept an Array type with unrelated elements

I have a function that resembles the following mock: // All properties in this type are optional. interface MyType { a?: string } // The return result type of `cb` is kept as the final result type. const f = <T extends ReadonlyArray<MyType>> ...

Service workers do not support fetching from .html files

Struggling with creating a functioning service worker for offline use has been a challenge. Despite trying numerous examples, the success has remained elusive. Initially, I suspected that the dynamic nature of my PHP-based website was causing the issue, or ...

Discover how to validate a property within an array of objects and add the accurate values to a fresh array using TypeScript

I have a list of objects and I want to create a new array that contains only the objects with the 'read' property set to true. I've tried a couple of different methods, but I keep getting an error: Uncaught TypeError: Cannot read properties ...

What is the duration since the last entry was recorded in mongoDB?

Recently, I've been working with this Mongoose Model. const GoalSchema = new Schema({ . . . . Date: { type: Date, default: Date.now } . . . . }); As part of my project, I am tasked with determin ...

Exploring the inner workings of AngularJS SEO in HTML5 mode: Seeking a deeper understanding of this hidden functionality

There are plenty of resources available for incorporating SEO-friendly AngularJS applications, but despite going through them multiple times, I still have some confusion, especially regarding the difference between hashbang and HTML5 mode: In hashbang (# ...

Instructions on creating the effect of rainwater cascading over text and spilling onto a webpage

Is it possible to make the rain flow over my text? Below is the code snippet from my JSFiddle: function strop(cleft, ctop, d) { var drop = document.createElement('div'); drop.className = 'punct'; drop.style.left = cleft + & ...

Identifying the Type of Element Based on Its Identifier

I have a function in JavaScript called testElement() that is triggered by the onclick event. <script type = "text/javascript"> function testElementType(element){ var elemId = $(element).attr("id"); //Can I determine the ' ...

explore a nested named view using ui-router

My app has a view called mainContent. <div class = "wrapper" ui-view = "mainContent"> </div> There is only one route for this view. $stateProvider .state("home", { url: "/home", vi ...

Dropdown Selection for International Telephone Input

The International Telephone Input plugin is beneficial, but it only allows for input. Users are not able to modify after selecting countries. I am interested in using it as a dropdown rather than an input field, so I made the following change: <input i ...

What is the method for filtering out specific fields in a template string?

I am currently working on defining constraints for the method field type event = { [k: `on${string}`]:(e:string)=>void } However, I need the event argument to be a number for fields that do not begin with 'on' type event = { [k: ` ...

The Body-Parser function returns an undefined value

In my server.js file, I have implemented user authentication using the following code: //API ROUTES var apiRoutes = express.Router(); //route to auth user apiRoutes.post('/authenticate', function(req,res){ //find the user User.findOne({ ...

Using the length of an array as an iterator within a nested ngFor loop in Angular 9

I am looping through an array of objects where each object contains another array of objects with attributes like "name" and "id". The length of this array of objects (noticias) varies. I am struggling to display these values and have only managed to acce ...

Encountering issues while retrieving data from a JSON object

Having trouble retrieving information from a JSON object using JavaScript and jQuery. I keep receiving an exception indicating that "code" is not set. My goal is to extract a country code from a string and automatically populate an input field based on the ...