NodeJS 在TypeScript类继承中调用方法时发生TypeError [重复]

5lhxktic  于 9个月前  发布在  Node.js
关注(0)|答案(1)|浏览(98)

此问题在此处已有答案

How to access the correct this inside a callback(15个答案)
How does the "this" keyword work, and when should it be used?(22个回答)
8天前关闭
我正在使用TypeScript开发Node.js应用程序,其中我有一个基类控制器(BaseController)和一个派生控制器(SettingController)。派生控制器应该使用基类的方法,但是当从SettingController的示例调用Ok方法时,我收到以下错误:
TypeError:无法读取未定义的属性(阅读“OK”)

**验证码:**SettingController.ts:

import { Request, Response, NextFunction } from 'express';
// ... other imports

export default new class SettingController extends BaseController {

    constructor() {
        super();
    }

    async SettingOTP(req: Request, res: Response, next: NextFunction) {
        try {
            // ... Some operations
            return this.Ok(res, 'OTP setting updated successfully');
        } catch (error: any) {
            this.BadRerquest(res, error.message);
        }
    }

    // ... other methods
}

字符串

BaseController.ts:

import { Response } from 'express';
// ... other imports

    export class BaseController {
    
        // ... constructor and other methods
    
        Ok<T>(res: Response, message: string) {
            return new SuccessResponse(message).send(res);
        }
    }

**尝试次数:**我已经确保BaseController被正确导入,并且Ok方法被定义并且没有被覆盖。我已经尝试在SettingController的构造函数中绑定方法,并且我确保TypeScript编译没有问题。
**问题:**为什么在SettingController方法中调用this.Ok时遇到TypeError,如何解决此问题以正确使用TypeScript中的继承方法?
更新

import express, { Express, Router, NextFunction, Request, Response } from 'express';

import SettingController from '../../http/controller/SettingController';

// const setting_controller = new SettingController(new SettingService());

const settingRouter = express.Router();
// settingRouter.get('/get', settingController.getSetting);
settingRouter.put('/opt-setting', SettingController.SettingOTP);

8ehkhllq

8ehkhllq1#

您应该只使用export default class SettingController extends BaseController而不是export default new class SettingController extends BaseController

相关问题