【问题标题】:Angular 2, v6: Write on assets/*.json file and save it [Typescript]Angular 2,v6:在 assets/*.json 文件上写入并保存 [Typescript]
【发布时间】:2018-11-03 02:05:46
【问题描述】:

:)

我有一个 Angular 应用程序(@angular/cli:~6.0.3,typescript:~2.7.2),它在 assets 文件夹中有一个 json 文件。 我正在尝试访问此 json 文件,在其上写入并保存。

我该怎么做?

这是我已经尝试过的:

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);
    }

为了测试,我使用:

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));
  }

当我执行 this.jsonService.getJson().subscribe((res: Food) => console.log(res)); 时,我输出了没有早期发布的新食物的 json。

【问题讨论】:

  • 你不能只在这样的静态文件中插入数据
  • 感谢@Vikas 的回答。有没有办法打开和修改本地存储的json文件?
  • 不,不是没有服务器端代码
  • 谢谢。问题解决了。

标签: json angular typescript angular2-http


【解决方案1】:

您不能在资产文件上写入。你可以使用

JSON.stringify()

JSON.parse()

并将数据存储在本地存储中

【讨论】:

    猜你喜欢
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多