gpt4 book ai didi

javascript - localStorage 似乎在 Angular 中不起作用

转载 作者:行者123 更新时间:2023-11-28 17:13:33 25 4
gpt4 key购买 nike

我有一个简单的服务,可以使用 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();
}

}

常量注释:

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

关于javascript - localStorage 似乎在 Angular 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com