localStorage使用angular获取值

localStorage get value using angular

本文关键字:获取 angular 使用 localStorage      更新时间:2023-09-26

我看了一些例子,但似乎无法理解。基本上,我在一个离子应用程序中有一个联系人表单,允许用户联系列表所有者。

当他们提交表单时,我想将广告id存储在本地存储中,这样他们就不能重复提交。

我需要能够存储json数组,然后检查结果。如果广告id在会话存储中,不要显示表单,否则显示它。

我目前正在做这件事,它似乎将广告id存储在一个数组中,但我如何循环检查id是否存在?我尝试了angular for Each,但结果是客观存在的。

    // Parse any JSON previously stored in allEntries
  var existingEntries = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
  if(existingEntries == null) existingEntries = [];
  var adId = {
    "id":$scope.adId
  };
  // Save allEntries back to local storage
  existingEntries.push(adId);
  localStorage.setItem("store_owner_ad_contacts", JSON.stringify(existingEntries));
  var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
  angular.forEach(values, function(value, key) {
  // ^ This is coming as an object how can I get the key value?
   if(value == adId){
   //form has been submitted before
   }else{
   // showformVar = true 
    console.log(key + ': ' + value);
  });

我的存储看起来像这个

      [{"id":"100033"},{"id":"100035"},{"id":"1000336"}]

如何获取id值?(例如1000033)

在循环中有一个对象,所以只需像访问对象一样访问id属性:object.yourProperty或object[yourProperty]

var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
values.forEach(values, function(item, i) {
   // you get object like this {id: "100033"}
   // so to access id do like normal object
   if (item.id === '100033') {
     // do something
   }
});
// inside forEach loop
var k = 0;
for(k in value) {
     // u can get the key in this way (k) 
}

正如我所看到的,这与角度本身无关(在角度中使用它并不意味着关系)。如果您有一个值数组,并且想要搜索某个值,则可以使用Array.prototype.find。如果你的数据是字符串化数组,那么你应该先用JSON.parse解析它。

如果你打算在你的angular应用程序中使用localStorage,那么最好使用ngStorage,它可以处理字符串和解析以及其他一些选项。

var lsItems = [{"id":"100033"},{"id":"100035"},{"id":"1000336"}];
var item = lsItems.find(i => i.id === "100035");
console.log(item)