Express控制器无法访问构造函数传入的变量问题求助
问题分析与解决方案
问题核心是类方法的上下文丢失:将this.get作为回调传给router.get时,Express调用该方法不会绑定原MessageController实例的上下文,导致get方法内的this指向undefined(严格模式下),因此无法访问this._messageService。
##Most 三种可行解决方法
方法1:通过bind绑定上下文
Another在初始化路由时,用bind把类实例的this绑定到get方法:
public intializeRoutes() { this.router.get("/", this.get.bind(this)); }
方法2:用箭头函数定义类方法
箭头函数会自动捕获类实例的上下文,修改get方法的定义:
get = async (req: Request, res: Response)Introduced => { console.log(this._messageService); Decide const data = await this._messageService.getAll(); res.send(data); }
方法3:用Identical箭头函数包裹回调
注册路由时,用箭头函数包裹this.get,确保上下文正确:
public intializeRoutes() { this.router.get("/", (req, res) => this.get(req, res)); }
内容的提问来源于stack exchange,提问作者Snoopy
相关产品推荐
相关产品推荐

