1

:)

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.

4
  • 1
    You can't just insert data in a static file like that Commented May 24, 2018 at 3:09
  • Thanks for the answer, @Vikas. Is there no way to open and alter a json file stored locally? Commented May 24, 2018 at 11:04
  • Nope Not without a server side code Commented May 24, 2018 at 12:46
  • Thank you. Question solved. Commented May 24, 2018 at 12:59

1 Answer 1

0

You can not write on assets files. you can use

JSON.stringify()

and

JSON.parse()

and store data in localStorage

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.