Angular 2, v6: Write on assets/*.json file and save it [Typescript]

4.2k Views Asked by At

:)

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.

1

There are 1 best solutions below

0
Mohamed Ramadan On

You can not write on assets files. you can use

JSON.stringify()

and

JSON.parse()

and store data in localStorage