【问题标题】:How to access values from keys from Local Storage in AngularJs?如何从AngularJs中本地存储的键中访问值?
【发布时间】:2016-03-13 05:55:23
【问题描述】:

我想使用 AngularJs 以最简单的方式从我的 Local Storage 中的某些键中访问值。 在 Resources --> Local Storage 我有:

Key:myKey
Value:{ "layouts":[ other_things ],"states":{ other_things  },"storageHash":"fs4df4d51"}

我试过了:

console.log($window.localStorage.key(0).valueOf('layouts'));
  //or
console.log($window.localStorage.getItem('myKey'));

结果

我的钥匙

【问题讨论】:

  • 你好弗拉德,我建议使用为浏览器的 localstorage 编写的 localStorageService 模块,它有很大帮助。查看 url github.com/grevory/angular-local-storage
  • @katmanco 是的,谢谢,我看过那个模块。我想先测试一下,如果成功了,我会安装模块。

标签: javascript angularjs local-storage


【解决方案1】:

你可以这样做:

$window.localStorage['myKey']

如果数据是字符串化的(读取:JSON.stringify)那么:

angular.fromJson($window.localStorage['myKey']);

【讨论】:

    【解决方案2】:

    LocalStorage 将值存储在字符串中,而不是对象中。您需要在分配对象之前对其进行序列化,并在获取时对其进行反序列化。

    var myObject= { "layouts":[ other_things ],"states":{ other_things  },"storageHash":"fs4df4d51"};
    
    // Stringify JSON object before storing
    localStorage.setItem('myKey', JSON.stringify(myObject));
    
    // Retrieve the object
    var myRetrievedObject = JSON.parse(localStorage.getItem('testObject'));
    

    【讨论】:

      【解决方案3】:

      从本地存储中获取 JSON 数据,因此需要将其解析为 JS 对象, JSON.parse($window.localStorage.myKey).layouts

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-23
        • 2016-09-16
        • 2021-03-16
        • 1970-01-01
        • 2018-09-26
        • 1970-01-01
        • 1970-01-01
        • 2021-04-05
        相关资源
        最近更新 更多