Angular2保存/加载JSON到本地存储

时间:2017-03-06 10:56:51

标签: json angular local-storage filereader

我正在尝试使用Angular2从用户计算机上的JSON文件中保存和加载数据。基本上我将用户的数据保存到LocalStorage。我想为他们添加一种备份数据的方法,以防他们出于某种原因需要清除浏览器。我正在使用HTML的File API来保存/加载。我可以成功地将LocalStorage中的JSON数据写入文件。但是,当我尝试将文件重新加载回LocalStorage时,所有引号都会以前面的反斜杠结束。

[{\"buildname\":\"\",\"unitname\":\"Jack\",\"id\":\"314\",\"rarity\":5,\"name_rarity\":\"jack-5\",\"createdOn\":\"2017-03-06T08:49:54.165Z\",\"totalHP\":2538,\"totalMP\":110,\"totalATK\":141}]

我正试图将它保存到LocalStorage,如下所示:

[{"buildname":"","unitname":"Jack","id":"314","rarity":5,"name_rarity":"jack-5","createdOn":"2017-03-06T08:49:54.165Z","totalHP":2538,"totalMP":110,"totalATK":141}]

继承我的app.component.ts文件:

builds = [];
      backUpData()
    {
      var textToSave = localStorage.getItem('builds');
      var textToSaveAsBlob = new Blob([textToSave], {type:"octet/stream"});
      var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
      var fileNameToSaveAs = 'newsavetotext.json'
      var downloadLink = document.createElement("a");
      downloadLink.download = fileNameToSaveAs;
      downloadLink.innerHTML = "Download File";
      downloadLink.href = textToSaveAsURL;
      downloadLink.style.display = "none";
      document.body.appendChild(downloadLink);

      downloadLink.click();
    }

    changeListener($event) : void {
      this.loadData($event.target);
    }

    loadData(inputValue: any) {
      var file:File = inputValue.files[0];
      var myReader:FileReader = new FileReader();
      myReader.onloadend = function(e){
        localStorage.setItem('builds', JSON.stringify(myReader.result));
        console.log(myReader.result);
      }
      this.builds = JSON.parse(localStorage.getItem('builds'));
      myReader.readAsText(file);
    }

我的app.component.html:

<button type="button" name="button" (click)="backUpData()">Back Up Data</button>

<div>
  Select file: <input type="file" (change)="changeListener($event)">
</div>

我无法弄清楚我做错了什么。

0 个答案:

没有答案