如何修复我的书签本地存储服务

时间:2019-08-05 09:05:30

标签: javascript angularjs

“我的书签服务”无法使用JSON结构存储结果项。 问题可能出在与本地存储功能不兼容的阵列上。

我尝试用JSON.stringify我的物品。


    var key = 'fud_bookmarks';
    var bookmarks = [];

    this.addBookmark = function(resultItem) {
      var bookmarks = this.getBookmarks();
      bookmarks.push(resultItem);
      return setBookmarks(bookmarks);
    };

    this.deleteBookmark = function(resultItem) {
      var bookmarks = this.getBookmarks();
      var i = bookmarks.indexOf(resultItem);
      if (i >= 0) {
        bookmarks.splice(i, 1);
        console.log(bookmarks)
        return setBookmarks(bookmarks);
      }
      return false;
    };

    this.getBookmarkCount = function() {
      return getBookmarks().length;
    };

    this.getBookmarks = function() {
      var bookmarks = localStorage.getItem(key);

      if (!bookmarks) {
        bookmarks = [];
      }

      return bookmarks;
    }


    function setBookmarks(bookmarks) {
      return localStorage.setItem(key, bookmarks);
    }

结果项目如下所示。


    {
      id: "112",
      docType: "doctyp117",
      title: "Abschließender Bericht über die Arbeit des Kunsts…- September 1944, Exemplar für Tieschowitz, o.D.",
      type: "Archivbestand",
      description: null,
      …
    }

    $$hashKey: "object:455"

    archive: {
      id: "24",
      title: "Familienarchiv der Grafen Wolff Metternich zur Gracht"
    }

现在我在控制台中收到此错误=>

bookmarks.push is not a function
    at Object.addBookmark (bookmark.js:12)

2 个答案:

答案 0 :(得分:1)

尝试以下操作::检查typeof书签是否不是对象,然后返回空数组。由于Array也是javascript中一种特殊的对象类型。

this.getBookmarks = function() {
      var bookmarks = localStorage.getItem(key);
      if (typeof bookmarks !== "object") {
        bookmarks = [];
      };

    return bookmarks;
    };

答案 1 :(得分:1)

localStorage存储字符串值,而不是对象。 如果要存储数组,请对其进行字符串化。

long long
function setBookmarks(bookmarks) {
   return localStorage.setItem(key, JSON.stringify(bookmarks));
}

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

如果starage中的值不是有效的JSON this.getBookmarks = function () { var bookmarks = JSON.parse(localStorage.getItem(key)); ... 方法,则会引发错误,因此您可以使用try catch来避免错误:

JSON.parse

deleteeBookmark应该看起来像:

this.getBookmarks = function () {
  var bookmarks;

  try {
    bookmarks = JSON.parse(localStorage.getItem(key));
  } catch (e) {
    bookmarks = [];
  }
...