Reputation: 3400
I have service called "sharedData" with some functions, how to call one of these functions from another such functions? here the code(marked trouble functions with "???????"): Thanks
service('sharedData', function ($http) {
var refillList = [];
var orderCart = {
orderPlace: null,
orderList: [],
totalSum: 0
};
return {
....
addRefill: function(value) {
...here some logic....
},
addOrder: function(order) {
...here some logic....
},
sendOrder: function(order, refill) {
$http.get(config.urls.ajaxOrder + "{\"order\":{\"table_id\":" + orderCart.orderPlace + ",\"item_id\":" + order.id + ",\"amount\":1,\"action\":1}}").success(function(dataDetails) {
if (dataDetails.success) {
if (refill == 1) {
// Filling refill list
??????????????????this.addRefill(order);?????????
}
// Filling order cart
?????????this.addOrder(order);?????????????
}
});
}
};
}).
Upvotes: 18
Views: 16711
Reputation: 8829
You should save reference to this
.
var self = this;
is a common practice.
sendOrder: function(order, refill) {
var self = this;
$http.get(config.urls.ajaxOrder + "{\"order\":{\"table_id\":" + orderCart.orderPlace + ",\"item_id\":" + order.id + ",\"amount\":1,\"action\":1}}")
.success(function(dataDetails) {
if (dataDetails.success) {
if (refill == 1) {
// Filling refill list
self.addRefill(order);
}
// Filling order cart
self.addOrder(order);
}
}
});
}
Now, with ES6 you can use arrow functions like this:
sendOrder: function(order, refill) {
$http.get(config.urls.ajaxOrder + "{\"order\":{\"table_id\":" + orderCart.orderPlace + ",\"item_id\":" + order.id + ",\"amount\":1,\"action\":1}}")
.success(dataDetails => {
if (dataDetails.success) {
if (refill == 1) {
// Filling refill list
this.addRefill(order);
}
// Filling order cart
this.addOrder(order);
}
}
});
}
Arrow functions doesn't change a context, so this
will be the same this
.
MDN article about arrow functions
Upvotes: 32
Reputation: 1509
The problem is that this in this callback function refers to the parent container of the callback which is $http in this case. What you'll want to do is create an instance of the parent object outside of the callback and reference that from within the callback.
Something like:
....
{
....
addRefill: function(value) {
...here some logic....
},
addOrder: function(order) {
...here some logic....
},
sendOrder: function(order, refill) {
var rootObj = this;
$http.get(config.urls.ajaxOrder + "{\"order\":{\"table_id\":" + orderCart.orderPlace + ",\"item_id\":" + order.id + ",\"amount\":1,\"action\":1}}").success(function(dataDetails) {
if (dataDetails.success) {
if (refill == 1) {
// Filling refill list
rootObj.addRefill(order);
}
// Filling order cart
rootObj.addOrder(order);
}
});
}
};
....
This is of course just a solution but the main concept to keep in mind is that the function is being called from the success promise not from your object.
Upvotes: 3