简体   繁体   中英

Call to a method stored in a variable in Typescript

In an Angular 2 app, I'm trying to store a method in a variable but calling it always throws an error. I'll explain it better below:

I have to call to 3 different API methods for updating the database, depending on the user's type: customer, collaborator or provider. This is what I have right now:

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

Each function is a call to http.put that return an Observable. When I run the above code I get:

TypeError: Cannot read property 'http' of undefined

I think it's because just calling the function doesn't set the appropiate 'this' value but I'm not sure...

Is there a way to do what I want? Thanks!

You loose context when you detach method from base object. As a result this.http in your services is undefined .

This should work:

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

You could also shorten it with bind operator (might need transform-function-bind babel plugin):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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