【问题标题】:localStorage does not seem to work in AngularlocalStorage 似乎在 Angular 中不起作用
【发布时间】:2019-05-27 02:10:15
【问题描述】:

我有一个简单的服务,它通过使用 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"}
];

【问题讨论】:

  • 您似乎正在用NOTES 中的内容覆盖NotesService 的构造函数中的localStorage notes。您刷新页面,应用程序重新初始化服务。

标签: javascript angular local-storage angular2-services


【解决方案1】:

您在每次刷新时覆盖数据,您需要检查是否存在。试试这样:

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

【讨论】:

  • 这个答案更有意义。按照我的建议合并没有效果,因为如果服务是单例服务,NOTES 变量在构造时已经为空。但是由于它使用的是localStorage,所以它应该是一个单例。所以,这个答案应该被标记为接受。
  • 因此,如果我正确理解了这一点,那么 NOTES const 数组实际上并没有得到更新。但只有它的“localStorage 版本”,这就是为什么在构造函数中将其设置为 NOTES 也会擦除 localStorage?
【解决方案2】:

这是因为您在构造函数中将NOTES 变量分配给本地存储。在每次页面重新加载时,它都会将空数组替换为本地存储数据。

你可以这样做:

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

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

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 1970-01-01
    • 2019-12-02
    • 2017-04-12
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    相关资源
    最近更新 更多