簡體   English   中英

本地存儲似乎在Angular中不起作用

[英]localStorage does not seem to work in Angular

我有一個簡單的服務,該服務通過使用localStorage獲取和設置本地NOTES對象數組中的項,但是每次頁面刷新之前輸入的數據都會丟失,並且僅保留const NOTES數組中的初始數據。 我不知道我在做什么錯。

服務代碼:

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

}

組件代碼:

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注意:

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

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

您在每次刷新時都會覆蓋數據,需要檢查是否存在。 嘗試這樣:

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

這是因為您將NOTES變量分配給了構造函數中的本地存儲。 在每次重新加載頁面時,它將用本地存儲數據替換空數組。

您可以像這樣:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM