2016-07-14 76 views
1

我知道我無法使用javascript將數據保存到文件,但有沒有解決方案可以在本地文件系統上創建配置文件(JSON),我可以在其中寫入數據,像添加或刪除對象一樣進行更改並保存。當我下次啓動我的應用時,我不想丟失新的數據。有任何想法嗎?創建配置文件 - 讀取和保存更改的能力

感謝您的幫助。

UPDATE

我想用它在不同的計算機。

+0

我想保留本地文件系統上的配置。 – Verri

+0

可能會使用mongodb以JSON存儲 – Rikin

+1

[localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)是您在此處需要的。或者查看[FileSystem API](http://www.html5rocks.com/en/tutorials/file/filesystem/)。 [你有什麼嘗試](http://whathaveyoutried.com)? – ManoDestra

回答

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舉例使用

+0

感謝您的回答!我喜歡這個想法,我將100%用於個人設置,但是當我想要在其他計算機上工作時,我需要其他全局設置。 – Verri