1

I'm trying to test out html5 localStorage feature. For some reason, whenever I try to retrieve a value from storage after refreshing the page, i dont get any value. Values are getting stored locally on my click functionality. But when i refresh the page, it doesnt show the values.

src/app.component.ts File

import { Component } from '@angular/core';

export class MyItems {
  value: string;
  constructor(value:string){
    this.value = value;
  }
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  title = "Working with Angular";
  myItems: MyItems[] = new Array();
  IsForUpdate: boolean = false;
  newItem: any = {};
  updatedItem;

  constructor(){
    this.myItems.push(    
      new MyItems("First Value"),    
      new MyItems("Second Value"),    
      new MyItems("Third Value"),    
      new MyItems("Forth Value"),    
      new MyItems("Fifth Value")    
    );
    localStorage.setItem("Values", JSON.stringify(MyItems));
    var getValues = localStorage.getItem("Values");        
  }
      
  AddItem() {    
    this.myItems.push(    
      this.newItem    
    );    
    this.newItem = {};
    localStorage.setItem('dataSource', this.newItem);
    localStorage.getItem('dataSource');    
    // console.log(localStorage.getItem('dataSource'));
  }  
 

  EditItems(i){
    this.newItem.value = this.myItems[i].value;
    this.updatedItem = i;
    this.IsForUpdate = true;
  }



  UpdateItem(){
    let data = this.updatedItem;
    for(let i=0; i < this.myItems.length; i++){
      if(i == data){
        this.myItems[i].value = this.newItem.value;
      }
    }
    this.IsForUpdate = false;
    this.newItem = {};
  }

 
  DeleteItem(i) {
    var confirmMe = confirm('Do you want to Delete it ?');
    if(confirmMe == true){
      this.myItems.splice(i, 1); 
    } else {
      alert("You cancelled the Operation");
    }  
  }
}
trincot
  • 317,000
  • 35
  • 244
  • 286
tkamath99
  • 629
  • 1
  • 12
  • 32

1 Answers1

2

If you are trying to store arrays or objects in localStorage, you will need to convert it into a string format, as localStorage only supports the storing of string values. You can use JSON.stringify() for that purpose.

localStorage.setItem('Values', JSON.stringify(this.newItem));

localStorage.setItem('dataSource', JSON.stringify(this.items));

Likewise, when you need to retrieve the item from localStorage, you can use JSON.parse() to convert it back into an array or object.

const storedItems = JSON.parse(localStorage.getItem('dataSource'));

On your constructor, you are overcomplicating the way you populate your array. After populating the myItems array, you can store it in your localStorage.

On your addItem() method, you can simply push the new items to your myItems array, and call localStorage.setItem(), which will overwrite the previous value stored on your Values key.

myItems: string[] = [];

constructor(){
  console.log(JSON.parse(localStorage.getItem('Values')));

  this.myItems.push('First Value', 'First Value', 'Third Value', 'Forth Value', 'Fifth Value');
  localStorage.setItem('Values', JSON.stringify(this.myItems));
}

addItem() {
  const newItem = ''; //replace that with any value you desire
  this.myItems.push(newItem)
  localStorage.setItem('Values', JSON.stringify(this.myItems));
}
wentjun
  • 40,384
  • 10
  • 95
  • 107
  • But how can i retrieve the items after addition in my code ? Can you pls help me in that – tkamath99 Mar 29 '19 at 06:23
  • @tkamath99 Are you referring to the code within your `AddItem()` method? Alright, what exactly do you want to retrieve? – wentjun Mar 29 '19 at 06:25
  • In the constructor i am adding the content in an array which displays in the frontpage within a box. So whenever i add a new item from AddItem() i want it to stay there even after page refresh – tkamath99 Mar 29 '19 at 06:38
  • Alright, and this.myItems contains this, right? `['First Value', 'Second Value', ...]` – wentjun Mar 29 '19 at 06:40
  • @tkamath99 yeah, I see. Alright, have you seen my the second part of my answer? – wentjun Mar 29 '19 at 09:27
  • Yes i tried it, but it is giving an error as 'Argument of type '"'' is not assignable to parameter of type 'Myitems' – tkamath99 Mar 29 '19 at 09:35
  • @tkamath99 is myItems an array of strings? Or can it contain other primitive data types such as numbers? – wentjun Mar 29 '19 at 09:37
  • It is just an array of strings – tkamath99 Mar 29 '19 at 09:37
  • If it is an array of strings, change your typecast and typecast it as `myItems: string[] = [];` – wentjun Mar 29 '19 at 09:38
  • Its done. I didnt typecast it to string. But rather i removed the push method from constructor. I compared it whether the localstorage was null and used getItem method to display the values from localstorage. Actually the array method in constructor was making all the chaos. – tkamath99 Apr 01 '19 at 07:22