【问题标题】:Create configuration file - ability to read and save changes [closed]创建配置文件 - 读取和保存更改的能力 [关闭]
【发布时间】:2016-07-14 15:32:38
【问题描述】:

我知道我无法使用 javascript 将数据保存到文件中,但是有什么解决方案可以在本地文件系统上创建配置文件 (JSON),我可以在其中写入数据、进行一些更改,例如添加或删除对象并保存它。当我下次启动我的应用程序时,我不想丢失我的新数据。有什么想法吗?

感谢您的帮助。

更新

我想在不同的电脑上使用它。

【问题讨论】:

标签: javascript json angular


【解决方案1】:

你可以给自己写一个SettingsService来通过localstorage读写数据:

class SettingsEntry {
    constructor(public key: string, public value: any) { }
}

export class SettingsService {
    private SETTINGS_KEY = "__SETTINGS__";
    private _settings: Array<SettingsEntry>;

    constructor() {
        let settings = localStorage.getItem(this.SETTINGS_KEY);

        if (settings && settings != undefined) {
            this._settings = JSON.parse(settings);
        }
        else {
            this._settings = [];

            this.save();
        }
    }

    private indexOf(key: string): number {
        for (let i = 0; i < this._settings.length; i++) {
            if (this._settings[i].key == key) {
                return i;
            }
        }

        return -1;
    }

    private save() {
        localStorage.setItem(this.SETTINGS_KEY, JSON.stringify(this._settings));
    }

    get(key: string) {
        let index: number = this.indexOf(key);

        if (index >= 0) {
            return this._settings[index].value;
        }

        return null;
    }

    set(key: string, value: any) {
        let index: number = this.indexOf(key);

        if (index >= 0) {
            this._settings[index].value = value;
        }
        else {
            this._settings.push(new SettingsEntry(key, value));
        }

        this.save();
    }
}

在您的组件或服务中像这样使用它:

_settingsService.set("time", new Date());

let time = _settingsService.get("time");

以工作Plunker为例使用

【讨论】:

  • 感谢您的回答!我喜欢这个想法,我会 100% 将它用于个人设置,但是当我想在其他计算机上工作时,我需要其他东西来进行全局设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 2012-02-15
相关资源
最近更新 更多