繁体   English   中英

Angular LocalStorage

[英]Angular LocalStorage

嗨伙计们我想用angularStorage保存一些信息,我向我的服务注入了$ 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;
    }])

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

我提前感谢你的帮助

存储时你做错了。 您正在用单个项目替换数组。 还有一点需要注意,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});
    };

您只需要更改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);

        };

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

作为建议,我建议你使用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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM