1

大家好,我正在尝试使用 localStorage 以角度保存一些信息,我将 $window 注入我的服务并创建了一个工厂调用 $localStorage

.factory('$localStorage', ['$window', function($window) {
        return {
            store: function(key, value) {
            $window.localStorage[key] = value;
            },
            get: function(key, defaultValue) {
            return $window.localStorage[key] || defaultValue;
            },
            storeObject: function(key, value) {
            $window.localStorage[key] = JSON.stringify(value);
            },
            getObject: function(key,defaultValue) {
            return JSON.parse($window.localStorage[key] ||     defaultValue);
            }
        }
        }])

我有其他工厂,我让我们使用 localStorage 工厂,以保存一些收藏夹

factory("favoriteFactory", ["$resource", "baseURL", "$localStorage", function($resource, baseURL, $localStorage) {
        var favFac = {};
        var favorites = $localStorage.getObject("favorites", "[]");

        favFac.addToFavorites = function(index) {
            for (var i = 0; i < favorites.length; i++) {
                if (favorites[i].id == index)
                    return;
            }

            $localStorage.storeObject("favorites", {id: index});
            //favorites.push({id: index});
        };

        favFac.deleteFromFavorites = function (index) {
            for (var i = 0; i < favorites.length; i++) {
                if (favorites[i].id == index) {
                    favorites.splice(i, 1);
                }
            }
        }

        favFac.getFavorites = function () {
            return favorites;
        };

        return favFac;
    }])

问题是当我添加一个最喜欢的项目时,它会在我的数组中替换自己,而不是在数组中添加一个新的,

我真的很感谢您的帮助

4

3 回答 3

2

您在存储时做错了。您正在用单个项目替换数组。还有一点需要注意的是, Array.prototype.push() 返回集合的长度。

enter code herefavFac.addToFavorites = function(index) {
        for (var i = 0; i < favorites.length; i++) {
            if (favorites[i].id == index)
                return;
        }
        favorites.push({id: index})
        $localStorage.storeObject("favorites", favorites);
        //favorites.push({id: index});
    };
于 2016-06-19T19:56:04.730 回答
1

你只需要改变addToFavorites方法

favFac.addToFavorites = function(index) {
            for (var i = 0; i < favorites.length; i++) {
                if (favorites[i].id == index)
                    return;
            }

            favorites.push({id: index});
            $localStorage.storeObject("favorites", favorites);

        };

现在它将首先添加一个项目,然后将您的数组保存到本地存储中。

于 2016-06-19T19:59:09.493 回答
0

作为一个建议,我建议您使用ngStorage,它使您能够像单个命令一样简单地从 localStorage 添加或删除项目:

$localStorage.favorites = [];

就是这样,现在您在 localStorage 中有收藏夹列表,并且无论何时修改此数组,您都将直接在 localStorage 上获得结果。

$localStorage.favorites.push(newItemToAdd); // this adds a item.
$localStorage.favorites = $localStorage.favorites
    .filter((v, i) => i !== indexOfItemToDelete); // removes item.
于 2016-06-23T00:36:47.863 回答