Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage get value using angular

I looked at some examples, but can't seem to figure this out. Basically I have a contact form in an ionic app that allows a user to contact a listing owner.

When they submit the form I want to store the ad id in local storage so they can't repeatability submit it over and over.

I need to be able to store json array and then check the results. If the ad id is in session storage don't show the form else show it.

I am currently doing this, which seems to store the ad ids in an array, but how do I loop through to check if an id exists? I tried angular forEach, but results come as an object.

    // 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);
  });

My storage looks like this

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

How do I get id value? (e.g 1000033)

like image 523
limit Avatar asked Jul 26 '16 05:07

limit


People also ask

How do I get localStorage value?

To get items from localStorage, use the getItem() method. getItem() allows you to access the data stored in the browser's localStorage object.

How do I get data from local storage in angular 8?

Save the Angular app and run the application. After the app gets loaded, type in localStorage from the browser console and you will be able to see the encrypted data in local storage. While trying to access the local storage data inside the application, you can get the decrypted data.


2 Answers

In your loop you have an object, so just access id property like you do with an object: object.yourProperty or 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
   }

});
like image 179
Gatsbill Avatar answered Oct 25 '22 12:10

Gatsbill


// inside forEach loop
var k = 0;
for(k in value) {
     // u can get the key in this way (k) 
}
like image 29
Sasank Sunkavalli Avatar answered Oct 25 '22 11:10

Sasank Sunkavalli