用Typescript实现Express Controller类 [英] implement express controller class with typescript
本文介绍了用Typescript实现Express Controller类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用打字稿制作快速应用程序。
路由器代码为:
I'm doing an express app with typescript. The router code is:
let user = new User();
router.get("/", user.test);
用户类别为
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?
推荐答案
您需要使用绑定函数,以保持 this $ c $的范围c>调用该方法时:
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));
或者您可以在 User
中执行此操作构造函数:
Or you can do that in the User
constructor:
export class User {
constructor() {
this.test = this.test.bind(this);
}
test(req, res, next) {
...
}
}
另一种选择是使用箭头功能:
let user = new User();
router.get("/", (req, res, next) => user.test(req, res, next));
这篇关于用Typescript实现Express Controller类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文