无法在路由Nodejs Express Typescript中的方法控制器内调用方法

Couldn't call method inside method controller in route Nodejs Express Typescript

我有两个类; authenticationRoutes.ts 和 authenticationController.ts。在我调用 'authenticationController.test' 的 authenticationRoutes 中,'authenticationController.test' 方法调用 'authenticationController.generateAccessAuthToken' 方法。每当我这样做时,我都会收到以下错误:Unhandled rejection TypeError: Cannot read 属性 'generateAccessAuthToken' 未定义

authenticationRoutes.ts
import { authenticationController } from '../controllers/authenticationController';

        //TEST ROUTE
        this.router.get('/users',  authenticationController.test);

authenticationController.ts


public test(req: Request, res: Response) {
        dbSequelize().User.findAll({
            where: {
                id: '0'
            },
            attributes: ['id']
        }).then((user: UserInstance[]) => {
            this.generateAccessAuthToken('0').then((response: any) => {
                console.log(response);
                res.send(response);
            });
        })
    }


generateAccessAuthToken(_id: any) {
        return new Promise(async (resolve, reject) => {
            await jwt.sign({ id: _id }, SECRET_KEY as string, function (err: Error, token: any) {
                if (err) {
                    reject(err);
                } else {
                    resolve(token);
                }
            })
        })
    }

我希望能够在不收到错误的情况下执行我描述的操作。

我认为这可以解决问题:

this.router.get('/users', authenticationController.test.bind(AuthenticationController));

基本上,当你有一个 class A 和一个方法 b 时,如果你传递 A.b 像:

const a = new A();
const b = a.b;
b(); // now 'this' is lost, any reference to `this` in b() code would be undefined

您正在传递仅函数。它现在与 A class 无关,它 只是一个函数 .

因此,除其他外,您可以使用 bind 显式设置函数的 this 上下文:

const a = new A();
const b = a.b.bind(a);
b(); // so now b() is forced to use a as this context

我敢打赌你的问题有很多重复项,但我无法快速找到任何人,因为搜索很棘手(this js 中的绑定有很多问题)。

希望这对您有所帮助。

我遇到了同样的问题并解决了它:

public test = (req: Request, res: Response) => {
        dbSequelize().User.findAll({
            where: {
                id: '0'
            },
            attributes: ['id']
        }).then((user: UserInstance[]) => {
            this.generateAccessAuthToken('0').then((response: any) => {
                console.log(response);
                res.send(response);
            });
        })
    }