You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JSON格式在LocalStorage存数据?存储位置及两类存储用途咨询

Hey there! Let's break down your questions one by one, using your existing Angular code as context:

1. Can I store created/edited data in LocalStorage using JSON format?

Absolutely! LocalStorage only supports storing string values, so JSON is the perfect way to serialize your note objects into a storable format. You'll just use JSON.stringify() to convert your Notes[] array into a string when saving, and JSON.parse() to convert it back into an object array when loading.

The best practice here is to put all LocalStorage logic in your NotesService, not in any component. Here's why:

  • Your service acts as the single source of truth for all note data. Any component (Edit, NotesList, or future components) that interacts with notes will go through the service, so storage logic only needs to be written once.
  • It keeps components clean—your Edit component only needs to handle UI input and call service methods, while your NotesList component only handles displaying data. Neither needs to worry about how data is persisted.

Modified NotesService Code (with LocalStorage Integration)

Here's how to update your service to handle LocalStorage:

import { Injectable } from '@angular/core';
import { Notes } from '../models/noteModel';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class NotesService {
  public notesChangeInDOM = new Subject<Notes[]>();
  private notes: Notes[] = [];

  constructor() {
    // Load saved notes from LocalStorage on service initialization
    const savedNotes = localStorage.getItem('notes');
    if (savedNotes) {
      this.notes = JSON.parse(savedNotes);
    } else {
      // Fallback to default notes if none are saved
      this.notes = [
        new Notes(
          'This Notes is related to the thing Dummy Content',
          new Date(2019,2,11,9,25,0),
          new Date(2019,2,11,9,25,0)
        ),
        new Notes(
          'The time that sun rises and sets is the most beautiful scene',
          new Date(2019,2,11,18,25,0),
          new Date(2019,2,11,18,25,0)
        ),
        new Notes(
          'The documents has to be uploaded to the cliets before the deadline',
          new Date(),
          new Date()
        ),
        new Notes(
          'Meeting has to be scheduled by this week',
          new Date(),
          new Date()
        ),
      ];
    }
  }

  setNotes(note:Notes[]){
    this.notes = note;
    localStorage.setItem('notes', JSON.stringify(this.notes));
    this.notesChangeInDOM.next(this.notes.slice());
  }

  getAllNotes(){
    return this.notes.slice()
  }

  getNoteById(id:number){
    return this.notes[id]
  }

  addNewNote(note:Notes){
    this.notes.push(note);
    localStorage.setItem('notes', JSON.stringify(this.notes));
    this.notesChangeInDOM.next(this.notes.slice());
  }

  editNote(id:number, note:Notes){
    this.notes[id] = note;
    localStorage.setItem('notes', JSON.stringify(this.notes));
    this.notesChangeInDOM.next(this.notes.slice());
  }

  deleteNote(id:number){
    this.notes.splice(id,1);
    localStorage.setItem('notes', JSON.stringify(this.notes));
    this.notesChangeInDOM.next(this.notes.slice());
  }
}

3. What are the main use cases for LocalStorage vs SessionStorage?

Both are part of the Web Storage API, but they differ in persistence:

  • LocalStorage:

    • Persists data indefinitely until it's manually deleted (either by the user clearing browser storage, or your code calling localStorage.removeItem()/localStorage.clear()).
    • Data is shared across all tabs/windows of the same origin.
    • Ideal for storing data that needs to survive browser restarts, like user preferences, offline app data, or (in your case) saved notes.
  • SessionStorage:

    • Only stores data for the current browser tab session. When the tab is closed, the data is automatically cleared.
    • Data is isolated to the specific tab—it's not shared with other tabs of the same origin.
    • Great for temporary data that doesn't need to be saved long-term, like form drafts that only matter during the current browsing session, or temporary session state.

内容的提问来源于stack exchange,提问作者Keerthana Bolloju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:45:09