Ionic列表中用LocalStorage存储含对象数组遇阻求助
解决LocalStorage存储对象数组后无法在ion-list展示的问题
我来帮你搞定这个问题!核心原因其实很直白:LocalStorage只能存储字符串类型的数据,你直接把数组存进去的时候,浏览器会自动调用数组的toString()方法,结果就变成了类似"[object Object]"的字符串,所以取出来自然不是数组,ion-list当然没法遍历展示啦。
下面是修正后的完整方案:
1. 修正数据存储与读取逻辑
你原来的代码每次调用addPlaylistAll都会新建空数组,这样只能保存最后一个添加的对象,还要解决序列化的问题。修改后的Manager.js代码如下:
playlistService.addPlaylistAll = function (presentation) { console.log("setting item"); // 先取出LocalStorage中已有的播放列表数据,没有的话初始化为空数组 var playlistarraytest = JSON.parse(localStorage.getItem('playlisttest')) || []; // 将新的presentation对象加入数组 playlistarraytest.push(presentation); console.log("array updated!! ", playlistarraytest); // 把数组序列化为JSON字符串后存入LocalStorage localStorage.setItem('playlisttest', JSON.stringify(playlistarraytest)); playlistService.refresh(); // 读取时记得反序列化为数组 var test = JSON.parse(localStorage.getItem('playlisttest')); console.log(test); // 现在控制台输出的就是正常的数组了 }
2. 确保视图能拿到正确的数组数据
在你的AngularJS控制器里,要把LocalStorage中存储的数据反序列化后赋值给$scope.playlist,这样ion-list才能正确遍历:
// 假设这是对应Playlist.html的控制器代码 angular.module('yourApp').controller('PlaylistController', function($scope) { // 初始化播放列表数据 $scope.playlist = JSON.parse(localStorage.getItem('playlisttest')) || []; // 同步refresh方法,确保刷新时能拿到最新的数组 playlistService.refresh = function() { $scope.playlist = JSON.parse(localStorage.getItem('playlisttest')) || []; }; });
关键知识点总结
- LocalStorage的API只支持字符串的存储和读取,任何非字符串类型的数据(比如对象、数组)都必须先通过
JSON.stringify()序列化为JSON字符串 - 读取数据时,必须用
JSON.parse()将JSON字符串反序列化为JavaScript对象或数组 - 存储新数据时,一定要先读取已有数据再追加,否则会直接覆盖之前的内容
内容的提问来源于stack exchange,提问作者Curtis Boylan
相关产品推荐
相关产品推荐

