2016-04-12 45 views
0
.factory("CountingService", function() { 
    var i = 0; 
    this.getNumber = (function() { 
     return i += i + 1; 

    })(); 

    return this; 
    }) 

我有这项服务来更新我的购物车号码,但它似乎没有得到最新的localstorage数据。因为我测试了我的控制器这样使用angularjs工厂的奇怪结果

console.log(CountingService.getNumber)甚至

$timeout(function(){ 

    console.log(CountingService.getNumber) 

},1000); 

我已经调试这几个小时。

+0

什么是'getItem'? – dfsq

+0

@dfsq修复了我的错字 –

+0

您应该明白,您的工厂初始化代码将执行一次。所以'getNumber'将代表工厂初始化时的值。你应该导出函数来获取新的数据。 –

回答

2

CountingService.getNumbergetItem?)是自调功能(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()) 
+0

固定我的错字大声笑.. –