2016-06-21 128 views
0

我使用本地存儲,當我試圖挽救一個數組,它會自動從對象將其轉換爲字符串具有類似於下面所示用離子一個問題:離子本地存儲

enter image description here

任何人都可以請幫幫我 ? 以下是我正在使用的代碼:

angular.module('mainApp') 
    .factory('cartFactory', function() { 
     var cart = [{ 
      'title': 'titre2', 
      'pic': './img/catalogue/k2.jpg' 
     }]; 
     console.log("Type 1:" , typeof(cart)); 
     console.log("Content 1:" , cart); 
     window.localStorage.setItem('cart', cart); 
     var cart = window.localStorage.getItem('cart'); 
     console.log("Type 2:" , typeof(cart)); 
     console.log("Content 2:" , cart); 

     return { 
      all: function() { 
       return cart; 
      }, 
      get: function (index) { 
       return cart[index]; 
      }, 
      add: function (product) { 
       cart.push(product); 
      }, 
      remove: function (product) { 
       var index = cart.indexOf(product); 
       cart.splice(index, 1); 
      } 
     }; 
    }); 

謝謝!

回答

2

的localStorage只支持字符串,你可能有最好的辦法是你的數組轉換成JSON數組,然後讀回:

localStorage.setItem("cart", JSON.stringify(cart)); 

//... 
var cart = JSON.parse(localStorage.getItem("cart")); 
+0

謝謝!那很簡單 – fzwael