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

Fel*_*Fel 2 javascript typescript angular

在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 });
Run Code Online (Sandbox Code Playgroud)

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

TypeError: Cannot read property 'http' of undefined
Run Code Online (Sandbox Code Playgroud)

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

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

dfs*_*fsq 7

从基础对象分离方法时松散上下文.因此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 });
Run Code Online (Sandbox Code Playgroud)

你也可以使用bind运算符缩短它(可能需要transform-function-bindbabel插件):

switch (user.type) {
    case OBJTYPES.CUSTOMER:
        updateAPIMethod = ::this.customerService.updateCustomer;
        break;
// ...
Run Code Online (Sandbox Code Playgroud)