2016-02-27 180 views
6

如何将多个对象存储到数组中然后存储到本地存储中,以便在需要时使用循环可以获取所有对象。Angularjs - 如何将对象存储在数组和本地存储中

例如对象:

var newMsg = { 
     sentDate: msgDate, 
     sentTime: msgTime, 
     msgTitle: "message title", 
     msgDesc: "message desc" 
    }; 

目前我使用https://github.com/grevory/angular-local-storage#configuration-example angularjs模块,而是奋力存储和从一个数组检索对象。

我曾尝试下面的代码:

msgArray = []; 
var savedMsgs = localStorageService.set("wimmtkey", newMsg); 

    msgArray.push(savedMsgs); 
    console.log(savedMsgs); 

这输出在控制台“真”,但期待看到存储的对象。另请建议循环访问数组以检索对象。谢谢。

+0

,则使用set方法在localStorage中设置数组。 当你想获得数组时,你将不得不使用get方法 – Akis

回答

4

一些更多的代码将是有用的,但对于angular-local-storage这是你将异物塞入数组保存数组中的localStorage前的样子:要推数组中的对象

var msgArray = []; 
var newMsg = { 
    sentDate: msgDate, 
    sentTime: msgTime, 
    msgTitle: "message title", 
    msgDesc: "message desc" 
}; 

//you can push all the objects here before saving to the storage 
//maybe you have a forEach here, pushing the objects? Who knows 
msgArray.push(newMsg); 

//the array is now set in the storage 
localStorageService.set("wimmtkey", msgArray); 

//the array obtained from local storage 
var obtained_array = localStorageService.get("wimmtkey"); 
一般
+2

你不需要使用这个库进行字符串化,因为'set'函数在引擎盖下利用了angular的'toJson()'方法。同样,'get'方法'JSON.parse()'是要返回的项目。不需要那个。 –

+0

感谢您的阅读,编辑答案 – Akis

+0

谢谢,按预期工作。 – GreenDome