Reputation: 8096
I'm trying to call a service function within another function of the same service, but seeing some strange behavior. Hopefully this is some obvious mistake I am overlooking. Here's the relevant part of my service:
app.factory('Data', ['$http', function($http) {
var Data = this;
var theProduct = {};
var seletedSku = {};
var uniqueItem = {};
return {
product: function(){
return theProduct;
},
getProduct: function(ext_id){
console.log(Data.product);
console.log(this.product);
},
}
}]);
As you can see, within the getProduct()
function, I am simply trying to log the product
function just to confirm the reference is working correctly. When getProduct()
is called, the first line logs undefined
, and the second line logs what I would expect, the product
function:
function (){
return theProduct;
}
Why is my reference not working? You can see towards the top of the service I save this
to the Data
variable. Any ideas?
I'm pasting the full service code below just for reference in case it helps:
app.factory('Data', ['$http', function($http) {
var Data = this;
var theProduct = {};
var seletedSku = {};
var uniqueItem = {};
return {
//return the current product being used in the app
product: function(){
return theProduct;
},
//get a products data from the server and set it as the current product being used by the app
getProduct: function(ext_id){
console.log(Data.product);
console.log(this.product);
return $http.post('get_product', {product_id: ext_id}).success(function(data){
theProduct = data;
//when a product is fetched, set the app's unique item
if(theProduct.unique_item){
Data.setUniqueItem(theProduct.unique_item);
}
else{
Data.setUniqueItem({});
}
});
},
//change the currently selected sku for the app
setSku: function(sku){
if(sku){
selectedSku = sku;
}
else{
//null was passed, meaning, the -- Selected SKU -- option
//was chosen, so reset selectedSku back to an empty object
selectedSku = {};
}
//when sku is set, also need to set current unique item
if(selectedSku.unique_item){
Data.setUniqueItem(selectedSku.unique_item);
}
else{
Data.setUniqueItem({});
}
return selectedSku;
},
//get the currently selected sku for the app
sku: function(){
return selectedSku;
},
//set the current unique item
setUniqueItem: function(item){
//before set a unique item, we need to check if the unique
//item we are setting is the same as the current unique item.
//if it is, we need to set them equal so the new item reflects
//current state of it since it's not repulling the item from the database
if(item.id != uniqueItem.id){
//only change the unique item if they are not the same
//if they are the same, just leave unique item as is
uniqueItem = item;
}
console.log(uniqueItem);
return uniqueItem;
},
//get the current unque item
uniqueItem: function(){
return uniqueItem;
}
}
}]);
Upvotes: 1
Views: 62
Reputation: 78006
Because at the time of the reference, this
has no context to itself as an object literal.
Upvotes: 1