Reputation: 453
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:
The JSON file:
{
"id": 1,
"firstName": "sampleName",
"lastName": "sampleLastName",
"car": {
"brand": "Toyota",
"model": "Vios",
"year": 2017
}
}
The save method:
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
Upvotes: 2
Views: 3006
Reputation: 453
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);
}
}
Upvotes: 1