简体   繁体   中英

localStorage does not seem to work in Angular

I have a simple service that gets and sets item in a local NOTES object array by using localStorage, but everytime the pages refreshes the data entered before is lost, and only the initial data in the const NOTES array remains. I don't know what I am doing wrong here.

Service code:

import { Injectable } from '@angular/core';
import { NOTES } from './localnotes';
import { INote } from './shared/interfaces';

const STORAGE_KEY = 'notes';

@Injectable({
 providedIn: 'root'
})
export class NotesService {


   constructor() { 
   localStorage.setItem(STORAGE_KEY, JSON.stringify(NOTES));
  }

  getNotes() {
   try {
     return JSON.parse(localStorage.getItem(STORAGE_KEY));
   } catch (e) {
     console.error('Error getting data from localStorage', e);
     return null;
   }
 }

deleteNotes() {

 }

 newNote(note: INote) {
    const tempnote = note;
    NOTES.push(tempnote);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(NOTES));
 }

}

Component code:

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

import { INote } from '../shared/interfaces';
import { NotesService } from '../notes.service';

@Component({
  selector: 'app-notes',
  templateUrl: './notes.component.html',
  styleUrls: ['./notes.component.css']
})
export class NotesComponent implements OnInit {
  notes: INote[];
  newNote: boolean = false;
  hideNewNote: boolean = false;


  constructor(private noteService: NotesService) {
    const data = noteService.getNotes();
    this.notes = data;
  }

  ngOnInit() {

  }

  makeNewNote() {
    this.newNote = true;
  }

  getValues(title, note, tag) {
      this.newNote = false;
      const tempnote = {title: title, note: note, date: new Date(), 
tag: tag};
      this.noteService.newNote(tempnote);
      this.notes = this.noteService.getNotes();
  }

}

const NOTES:

import { INote } from './shared/interfaces'; 

export const NOTES: INote[] = [
    {title: "title1", note: "note1", date: new Date(), tag: "tag1"}
];

You overwrite the data on each refresh, you need to check if exists or not. Try like this:

constructor() {
  if(!this.getNotes()){
    localStorage.setItem(STORAGE_KEY, JSON.stringify(NOTES));
  }
}

It is because you assign NOTES variable to local storage in constructor. In every page reload, it replaces the empty array with the local storage data.

You can do like:

constructor() { 
   let mergedValues = [...NOTES];
   const previousValues = localStorage.getItem(STORAGE_KEY);
   if(previousValues){
      mergedValues = [...JSON.parse(previousValues)];
   }

   localStorage.setItem(STORAGE_KEY, JSON.stringify(mergedValues));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM