1
我试图在同一服务的另一个功能内调用服务功能,但看到一些奇怪的行为。希望这是我忽略的一些明显的错误。这里是我服务的相关部分:服务功能内的角度呼叫服务功能,对此不起作用
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);
},
}
}]);
正如你所看到的,getProduct()
函数中,我只是试图登录该product
功能只是为了确认参考正常工作。当getProduct()
被调用时,第一线记录undefined
,第二行记录了我所期望的,product
功能:
function(){
return theProduct;
}
为什么不工作我参考?您可以看到服务的顶部,我节省了this
到Data
变量。有任何想法吗?
我下面粘贴仅供参考,全程服务代码的情况下,它可以帮助:
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;
}
}
}]);
是的,谢谢。我现在看到了。我想我应该只使用'this',然后如果我在回调中需要它,我可以在进入回调之前保存对它的引用。这听起来是对的吗? – flyingL123 2014-10-03 17:20:08
当然,你也可以使用'bind(this)':https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – AlienWebguy 2014-10-04 23:06:07