简体   繁体   中英

Overwriting local JSON file in Angular

I have a json file which I wish to modify. I already have a way of mapping it into a model but the thing is, I can't save it or overwrite the existing json file. I already tried file-saver but I learned that I won't be able to change is save directory since it depends on the setting of the browser.

I simply need to modify the json file on my assets folder so I can write a get method, which will return the modified json file.

I don't know what info I could provide but here's what I have so far:

{
    "id": 1,
    "firstName": "sampleName",
    "lastName": "sampleLastName",
    "car": {
        "brand": "Toyota",
        "model": "Vios",
        "year": 2017
    }
}

saveJson(arg) {
  const blob = new Blob([JSON.stringify(arg)], {type : 'application/json'});
  saveAs(blob,'test.json');
}

The arg parameter will receive the model which has the new set of data. This method always saves the new json file in the Downloads folder since that is where the browser points its downloaded files. I believe I have to change this one totally

Since I won't be able to change the directory of file saver, I looked for alternate solutions that will somehow provide the same solution. I simply used the local storage of the browser which I just discovered today. XD

Anyway, just in case a fellow beginner stumbles on the same problem and doesn't know how to use the local browser storage, here's the service I made:

import { Injectable } from '@angular/core';

@Injectable()
export class MockService {
  saveJson(id, obj) {
    localStorage.setItem(id, JSON.stringify(obj));
  }

  getJson(id) {
    return JSON.parse(localStorage.getItem(id));
  }

  removeJson(id) {
    localStorage.removeItem(id);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM