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

标签 javascript angular 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 });

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

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 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/

相关文章:

javascript - JavaScript 中的 For 循环缺少值

javascript - 启用/禁用丰富 :calendar with JavaScript doesn't work

generics - Typescript 泛型约束扩展了其他泛型类型

typescript - 类型不可分配给类型 2322

javascript - Protractor table.filter 超时

javascript - 将单独的按钮映射到单独的 CSS 文件以更改我页面的背景图像

javascript - 在 Typescript 中使用多个字符串数组

typescript - RxJs 从 observable 获取值(value)

angular - 让 angular-oauth2-oidc 从其他选项卡检索访问 token

javascript - 在 TinyMCE 4 中,editor.onBeforeSetContent.add() 已弃用,用什么代替?