[英]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. 我有一个简单的服务,该服务通过使用localStorage获取和设置本地NOTES对象数组中的项,但是每次页面刷新之前输入的数据都会丢失,并且仅保留const NOTES数组中的初始数据。 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: const注意:
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. 这是因为您将
NOTES
变量分配给了构造函数中的本地存储。 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.