2017-09-01 43 views
2

在角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调用返回可观察到的。当我运行上面的代码我得到:

TypeError: Cannot read property 'http' of undefined 

我想这是因为只是调用该函数不设置此时,相应的“本”的价值,但我不知道......

是否有如何做我想做的事?谢谢!

+0

你真的打算'invoke'在这条线的功能? :'... = this.collaboratorService.updateCollaborator();' – Arg0n

+0

具有u输入http模块从@角/ HTTP在哪里你使用HTTP服务 –

+0

你可能错过了'.bind(...)'或' =>'这打破了'绑定',但我没有看到r在你的问题中你通过函数做出更具体的建议如何修复的代码。 –

回答

4

您宽松背景下,当你从分离的基础对象的方法。因此您的服务中的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 operator缩短(可能需要transform-function-bind巴贝尔插件):

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