Error: Property 'mytest' is undefined and cannot be read

While working with Swagger API, I encountered an error message when calling the endpoint stating "Cannot read property 'mytest' of undefined"

class UserData {
  private mytest(req:any, res:any, next:any){
    return res.json('test32423423');

  }
  public loginByJSON(req: any, res: any, next: any) {
    this.mytest(req,res,next);
  }
}

const userData = new UserData();
export = {
  loginByJSON: userData.loginByJSON
};

Answer №1

Working with JavaScript function context can be tricky, but one important thing to remember is that when you reassign a function, it will adopt the context of the object it's assigned to. This means that `this` will point to the new object being created.

There are various approaches to maintaining this context, with one common method involving binding the function to the object instance:

{
  loginByJSON: user.loginByJSON.bind(user),
}

Another way is to use instance-bound methods like this:

loginByJSON = (req: any, res: any, next: any) => {
  this.mytest(req, res, next);
}

By using instance-bound methods, the method will always be linked to that specific instance. The downside is that a new function is created for each instance, but if you're only creating one instance and doing this for organizational purposes, it shouldn't be a major issue.

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

It is not possible to transform Next.js into a Progressive Web App (P

Can someone assist me with PWA implementation? I tried running npm run build, but it was unsuccessful. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbaacbface0abbfa2a3b98dfde3fce3fd">[email protected]</a> ...

Utilizing ES6 Map type in TypeScript for Angular 2 Response Data Transfer Object Definition

Is it possible to utilize the es6 Map type in an HTTP Response DTO? Let's consider an Angular 2 request: public loadFoos(): Observable<FoosWrapper> { return this.http.get("/api/foo") .map(res => res.json()); } Now, take a loo ...

What are the steps to resolve the "EADDRINUSE: address already in use :::3000" error in an integration test?

While testing my simple endpoint using jest and superTest in my TypeScript project, I encountered the listen EADDRINUSE: address already in use :::3000 error. The file app.ts is responsible for handling express functionalities and it is the one being impo ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

Challenges arise with dependencies during the installation of MUI

[insert image description here][1] I attempted to add mui styles and other components to my local machine, but encountered a dependency error. How can I resolve this issue? [1]: https://i.stack.imgur.com/gqxtS.png npm install @mui/styles npm ERR! code ERE ...

Develop an interactive React sidebar with changing elements

I'm in the process of developing a sidebar for a project, with the goal of making it similar to tools like Confluence. This means that we need the ability to rearrange documents and create subdirectory structures by simply moving the documents, with ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

What causes the discrepancy in errors when dealing with subtype versus regular assignments?

Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/ interface PartialCustomData { option?: number; } interface A { [key: string]: string | PartialCustomData; } interface B extends A { [k ...

Utilizing Typescript version 1.5 alongside window.event.ctrlKey

When I need to debug, I occasionally check if the ctrl key is pressed for certain secret actions. This check may be included in any function, not necessarily an event handler itself (it could be a callback or an event handler). In my TypeScript code, I us ...

What is causing the issue where search query parameters are not recognizing the initially selected option?

Hey, I'm having an issue with searchParams. The problem is that when I apply filters like "Breakfast, Lunch, Dinner", the first chosen option isn't showing up in the URL bar. For example, if I choose breakfast nothing happens, but if I choose lun ...

After updating to Angular 7, an error was encountered: "TypeError: Unable to execute map function on ctorParameters"

After updating my Angular project to version 7, I encountered a new issue. When running "ng serve --open" from the CLI, I received the following error message: Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities._own ...

Error encountered while utilizing the Extract function to refine a union

I am currently working on refining the return type of my EthereumViewModel.getCoinWithBalance method by utilizing the Extract utility type to extract a portion of my FlatAssetWithBalance union based on the generic type C defined in EthereumViewModel (which ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

Retrieve data from Ionic storage

Need help with Ionic storage value retrieval. Why is GET2 executing before storage.get? My brain needs a tune-up, please assist. public storageGet(key: string){ var uid = 0; this.storage.get(key).then((val) => { console.log('GET1: ' + key + ...

Incorporating AngularFire2 in the latest Angular 11.0.5 framework

I have been attempting to utilize Firebase as a database for my angular application. Following the guidance provided in these instructions (located on the official developers Github page), I first installed npm install angularfire2 firebase --save in my p ...

What is the best way to create buttons corresponding to the total number of "postId" properties in an array retrieved from an API call in Angular 10 using the "ngFor" directive?

export class AlphaComponent implements OnInit { apiData=[]; //array that stores API data constructor(private helpService:HelpService){ }; ngOnInit(){ this.fetchData() }; fetchData(){ this.helpService.getPostId().subscribe(( ...

The attribute 'prop' is not found on the type 'IntrinsicAttributes & TableProp'.ts(2322)

Encountering an error while trying to pass a prop to a React component for the first time. Despite looking at other posts for solutions, I have been unable to resolve it so far. Here is a snippet of my code: type TableProp = {}; function Table(prop: Tabl ...

Error with scoped slot typing in Vue3 using Vite and Typescript

I am currently working on a project using Vue3, Vite, and TypeScript as the devstack. I encountered an error related to v-slot that reads: Element implicitly has an 'any' type because expression of type '"default"' can't ...

The variable isJoi has been set to true but there is an error due to an unexpected

I am currently developing a NestJs backend on multiple machines. One of the machines is experiencing issues with the @hapi/joi package. When running the NestJs application in development mode on this specific machine, I encounter the following error: PS C ...