即使在使用箭头function的情况下,“这”在打字稿中也是未定义的
当我收到'catch'callback时,'this'是未定义的,即使使用箭头function。 有任何想法吗?
private all(req: Request, res: Response): void { EntityRepository.getRepositoty(req.params.etName).then(repo => { ... }).catch((err) => { this.handleError(res, err); // here I get undefined. }); }
如何调用所有的func。
它被称为基于快速路线。
添加了@ jfriend00build议的方法bind
。
constructor() { // Connect to database. DataAccess.connect(); // Starts configuring routes for api this.router = Router(); // Bad request due to absence of entity type. this.router.get("/", (req, res) => { res.statusCode = 400; res.statusMessage = SysMsgs.error.noEntityTypeSpecified.message; res.send(); }); // Added method 'bind'. this.router.get(this.routeBase, this.all.bind(this)); this.router.get(this.routeBase + "/:id", this.findOne.bind(this)); }
使用箭头函数, this
将保留它在箭头函数调用之前的范围内的值。 在你的情况下,这意味着它将在你all
函数开始时具有任何价值。 所以,这个值取决于如何调用all
函数。
而且,根据你的this.router.get()
指定this.all
作为callbackthis.all
,这意味着this
内部this.all
将被设置为Express在调用callbackthis.all
时设置的值。 而且,这是undefined
。
你可以通过使用.bind()
来解决你的问题。
this.router.get(this.routeBase, this.all.bind(this));
这将确保在.all()
运行时设置适当的值。 然后, all()
arrow
函数将使用这个值。
注意:您将需要使用.bind()
作为callback传递的任何方法,您希望this
是callback中的对象。 当你传递这样的东西时,这个值会丢失,只传递给方法的引用。 调用者然后调用该方法作为一个正常的function,没有对象绑定。 你使用.bind()
来控制你自己。 .bind()
本质上创build了一个小存根函数,通过调用你的方法来重新附加适当的指针。
你也可以为它创build自己的包装箭头function:
this.router.get(this.routeBase, (req, res) => this.all(req, res));
正如Saravana指出的那样,将保留TypeScripttypes检查。
虽然@ jfriend00的回答覆盖了你的代码的问题,在JavaScript中使用bind
没有任何问题,但是当你在TypeScript中使用bind
时候有一点问题。 bind
的types签名是:
bind(this: Function, thisArg: any, ...argArray: any[]): any;
注意, bind
返回any
意义closures返回的函数的任何types检查,这会导致微妙的错误。 以下面的例子为例:
// Assume the definition for `router.get` is something similar to this: get(routeBase: string, callback: (req: Request, resp: Response) => void) // ... and in the place you are calling it private all(param: number): void { } this.route.get(this.routeBase, this.all.bind(this)); // No compiler error, but `all` and the callback parameter expected by `route.get` don't match!
如果你想保持types检查,你可以使用下面的东西,而不是bind
:
this.route.get((req, resp) => this.all(req, resp));
请参阅: https : //github.com/Microsoft/TypeScript/issues/212
- 在TypeScript中基于string值属性对对象进行sorting
- 出现错误'在angular2应用程序中运行服务时,无法读取未定义的属性'长度'
- Angular找不到模块“net”
- 将parameter passing给TypeScript编译器Node模块
- 编译节点应用程序时出错 – variables'Promise'必须是'any'types,但是这里有'PromiseConstructor'
- 如何用sinon存根打字的一个类的私有方法
- Node / JS导入后立即创build新的实例
- 要求使用index.js文件夹
- 当使用angular version 2.4.9,typescript&webpack version 2.2.1时,属性'map'在types'Observable <Response>'上不存在