angular - 如何从 localStorage 输出数组?
问题描述
localStoage
我使用该save()
方法保存对数组的更改。我在remove()
andadd()
方法中使用它,并且元素被删除或添加到localStoage
。但是当我将this.Mycollection
存储我的静态数组getPictures()
的变量更改为添加或删除元素后动态显示数据的变量this.getCollection
时,更改仅在重新加载后发生页。另外,当我清除localStoage
然后我得到错误:
SyntaxError:位置 0 处 JSON 中的意外标记 u
我需要实现存储画廊条目,localStorage
以便在您重新加载页面时,删除或添加所有更改都会保存。
import {Injectable} from '@angular/core';
import {myCollection} from './gallery-data'; // my static array
import {Picture} from "./gallery-module/gallery/Picture"; // interface
@Injectable({
providedIn: 'root'
})
export class GalleryService {
Mycollection: Picture[] = myCollection;
getCollection = JSON.parse(localStorage["Collection"]);
constructor() {}
save() {
localStorage["Collection"] = JSON.stringify(this.Mycollection);
}
getPictures(): Picture[] {
return (this.Mycollection);
}
remove(picId: number): void{
this.Mycollection = this.Mycollection.filter(p => p.id !== picId);
this.save();
}
add(title: string, url: string): void {
const id: number = Math.max(0, ...this.Mycollection.map(({id}) => id)) + 1;
const post: Picture = {
title,
url,
id
};
this.Mycollection.unshift(post);
this.save();
}
}
解决方案
你得到了
位置 0 处 JSON 中的意外标记 u
因为JSON.parse
调用undefined
(localStorage["Collection"]
为空或根本没有设置)
推荐阅读
- dotnetnuke - 如何在调度程序的 DoWork() 方法中检索 DNN ModuleSetting 或 TabSetting?
- wordpress - Wordpress wp-content 插件不是管理员 add_menu_page
- html - 如何将网站背景设置为模糊的视频?
- javascript - 反应映射功能没有返回任何东西
- c# - Microsoft Graph 和 WPF 用户身份验证 - 自定义登录表单
- javascript - `document.documentElement` 的 offsetHeight 行为不同
- php - 从表中访问用户配置文件
- javascript - 如何计算几个总金额的总和?
- java - 从资源中读取文件 - 路径必须存在:/app/app.jar!/BOOT-INF/classes!/features/
- php - 419 页面在 laravel 5.7 中过期