Reputation: 81
:)
I have an Angular application (@angular/cli: ~6.0.3, typescript: ~2.7.2) which have a json file in assets folder. I'm trying to access this json file, write on it and save it.
How can I do that?
Here is what I already try:
private jsonPath = 'assets/foods.json';
public postJson(food: Food): Observable<Food> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this._http.post(this.jsonPath, food, httpOptions);
}
To test, I use:
public testJson() {
const food = new Food('name1', '361');
this.jsonService.postJson(food).subscribe(data => console.log('Post: ' + data));
this.jsonService.getJson().subscribe((res: Food) => console.log(res));
}
When I execute this.jsonService.getJson().subscribe((res: Food) => console.log(res));, I have as output the json without the new food that has been post early.
Upvotes: 1
Views: 4248
Reputation: 1
You can not write on assets files. you can use
JSON.stringify()
and
JSON.parse()
and store data in localStorage
Upvotes: 0