implement express controller class with typescript

后端 未结 2 377
無奈伤痛
無奈伤痛 2021-02-06 07:06

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

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

the user class is



        
2条回答
  •  隐瞒了意图╮
    2021-02-06 07:46

    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));
    

提交回复
热议问题