implement express controller class with typescript

淺唱寂寞╮ 提交于 2019-12-04 13:44:57

问题


I'm doing an express app with typescript. The router code is:

let user = new User();
router.get("/", user.test);

the user class is

export class User {
   test(req, res, next) {
      // this === undefined
   }
}

the problem is that the this object is undefined inside test method. Is there a better way to implement express routing?


回答1:


You need to use the bind function to keep the scope of this when the method is invoked:

let user = new User();
router.get("/", user.test.bind(user));

Or you can do that in the User constructor:

export class User {
    constructor() {
        this.test = this.test.bind(this);
    }

    test(req, res, next) {
        ...
    }
}

Another option is to use an arrow function:

let user = new User();
router.get("/", (req, res, next) => user.test(req, res, next));



回答2:


You can use export default and instantiate the controller so it can be used without instantiation in whichever file you've imported the controller.

register.controller.ts

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

class Register {

    constructor() {    
      this.register = this.register.bind(this);
    }

    register(req: Request, res: Response, next: NextFunction) {
      // ... removed for brevity
    }
}

export default new Register();

server.ts or auth.routes.ts

import registerCtrl from '../controllers/auth/register.controller.js';

// ... removed for brevity

router.post('/register', registerCtrl.register);


来源:https://stackoverflow.com/questions/40018472/implement-express-controller-class-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!