.factory("CountingService", function() {
var i = 0;
this.getNumber = (function() {
return i += i + 1;
})();
return this;
})
我有此服务来更新我的购物车号码,但似乎没有获取最新的本地存储数据。因为我在我的 Controller 上测试了它,就像这样
console.log(CountingService.getNumber )
甚至
$timeout(function(){
console.log(CountingService.getNumber )
},1000);
我已经调试了几个小时了。
最佳答案
CountingService.getNumber
(getItem
?) 是一个自调用函数 (IIFE)。您将此函数的结果分配给 CountingService.getNumber
。当代码第一次执行时会发生这种情况。这就是为什么当您稍后更改 localstorage 并再次调用 getNumber
时,您将看不到任何更改。试试这个:
.factory("CountingService", function() {
this.getNumber = function() {
if(localStorage.getItem('cart') != null){
var cart = JSON.parse(localStorage.getItem('cart'));
var totalItem = 0;
for(var i=0;i<cart.length;i++){
totalItem += cart[i].qty;
}
return totalItem;
} else{
return 0;
}
};
return this;
})
并像这样使用它:
console.log(CountingService.getNumber())
关于javascript - 使用 angularjs 工厂的奇怪结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36567432/