在 Angular 2 应用程序中,我试图将方法存储在变量中,但调用它总是会引发错误。我将在下面更好地解释它:
我必须调用 3 种不同的 API 方法来更新数据库,具体取决于用户类型:客户、合作者或提供者。这是我现在拥有的:
let updateAPIMethod;
switch (user.type) {
case OBJTYPES.CUSTOMER:
updateAPIMethod = this.customerService.updateCustomer;
break;
case OBJTYPES.COLLAB:
updateAPIMethod = this.collaboratorService.updateCollaborator;
break;
case OBJTYPES.PROVIDER:
updateAPIMethod = this.providerService.updateProvider;
break;
}
updateAPIMethod(user).subscribe( (ret) => { DEAL WITH SUCCESS },
(error) => { DEAL WITH ERROR });
每个函数都是对返回 Observable 的 http.put 的调用。当我运行上面的代码时,我得到:
TypeError: Cannot read property 'http' of undefined
我认为这是因为仅仅调用函数并没有设置适当的“this”值,但我不确定...
有没有办法做我想做的事?谢谢!
最佳答案
当你从基础对象中分离方法时,你失去了上下文。因此,您的服务中的 this.http
是 undefined
。
这应该有效:
let updateAPIMethod;
switch (user.type) {
case OBJTYPES.CUSTOMER:
updateAPIMethod = this.customerService.updateCustomer.bind(this.customerService);
break;
case OBJTYPES.COLLAB:
updateAPIMethod = this.collaboratorService.updateCollaborator.bind(this.collaboratorService);
break;
case OBJTYPES.PROVIDER:
updateAPIMethod = this.providerService.updateProvider.bind(this.providerService);
break;
}
updateAPIMethod(user).subscribe( (ret) => { DEAL WITH SUCCESS },
(error) => { DEAL WITH ERROR });
您也可以使用 bind operator 缩短它(可能需要 transform-function-bind
babel 插件):
switch (user.type) {
case OBJTYPES.CUSTOMER:
updateAPIMethod = ::this.customerService.updateCustomer;
break;
// ...
关于javascript - 调用存储在 Typescript 变量中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45998842/