:)

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.


You can not write on assets files. you can use

JSON.stringify()

and

JSON.parse()

and store data in localStorage


你不能像那样在静态文件中插入数据

感谢您的回答,@Vikas。有没有办法打开和更改本地存储的 json 文件?

不,没有服务器端代码

谢谢。问题解决了。