繁体   English   中英

调用存储在Typescript中的变量中的方法

[英]Call to a method stored in a variable in Typescript

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

每个函数都是对http.put的调用,返回一个Observable。 当我运行上面的代码时,我得到:

TypeError: Cannot read property 'http' of undefined

我认为这是因为只是调用函数并没有设置适当的'this'值,但我不确定...

有办法做我想要的吗? 谢谢!

从基础对象分离方法时松散上下文。 因此,您的服务中的this.httpundefined

这应该工作:

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运算符缩短它(可能需要transform-function-bind babel插件):

switch (user.type) {
    case OBJTYPES.CUSTOMER:
        updateAPIMethod = ::this.customerService.updateCustomer;
        break;
// ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM