Home > Software engineering >  Array is gone after refreshing page, even though I use LocalStorage?
Array is gone after refreshing page, even though I use LocalStorage?

Time:09-17

I call this add method in my template and I can add new objects into the eintraege-array. In the internet, it says that the LocalStorage is used that when I refresh the page, all my changes are being stored. But it doesn't. Below is the add method, which is called in a component and the add method calls another saveData method, which is coming from one of the LocalStorage-Methods. Please tell me, if you need more information. Hope this is enough

eintraege: Eintrag[] = [];
  
  add(beschreibung: string, faelligkeitsdatum: string) {

      var eintrag: Eintrag = {
        beschreibung: '',
        faelligkeitsdatum: '',
        erledigt: false,
      };

      eintrag.beschreibung = beschreibung;
      eintrag.faelligkeitsdatum = faelligkeitsdatum;
      eintrag.erledigt = false;

      this.eintraege.unshift(eintrag);

      this.eintragService.saveData('token', JSON.stringify(this.eintraege))

my service, which uses LocalStorage:

public saveData(key: string, value: string) {
    localStorage.setItem('token', value);
  }

EDIT: I do use the getItem-Method:

ngOnInit(): void {
    this.getEintraege();
  }
getEintraege(): void {
    this.eintragService.getData('token')
  }

and in my service it looks like this:

 public getData(key: string) {
    return localStorage.getItem(key)
  }

But as soon as I refresh the page, everything is gone.

CodePudding user response:

you supposed to have something like that in your component

ngOnInit() {
    this.eintraege = localStorage.getItem('token')
}
  • Related