首页 > 解决方案 > 如何从 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();

    }
}

标签: angulartypescriptlocal-storage

解决方案


你得到了

位置 0 处 JSON 中的意外标记 u

因为JSON.parse调用undefinedlocalStorage["Collection"]为空或根本没有设置)


推荐阅读