Reputation: 4818
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!
Upvotes: 2
Views: 4361
Reputation: 193271
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;
// ...
Upvotes: 8