2

I am building a simple Angular app.

I have some static data in a JSON file which I want to load.

I have put the file data.json under src.

I am trying to load it as follows

export class AppComponent {
  private urlDataFile = './data.json';

  constructor(
    private _http: HttpClient
  ) {
    this.loadData().subscribe((data) => {
      console.info(data);
    });
  }

  private loadData() {
    return this._http.get(this.urlDataFile);
  }
}

and am running my server with ng serve.

At runtime (on page load), I see the GET request to http://localhost:4200/data.json, and it results in a 404 NOT FOUND

I have tried putting this file elsewhere in the project - /src, /src/app, in the root of the project - with no success.

Where should this file be located? Or am I fundamentally doing it wrong?

Vihung
  • 12,947
  • 16
  • 64
  • 90

2 Answers2

1

you can simply use import:

import dataFile from'./data.json';

export class AppComponent {
  private urlDataFile = dataFile;

  constructor(
    private _http: HttpClient
  ) {
    this.loadData().subscribe((data) => {
      console.info(data);
    });
  }

  private loadData() {
    return this._http.get(this.urlDataFile);
  }
}
Nahom Ersom
  • 90
  • 1
  • 6
1

I worked on a project where we were doing something similar.

First, go to assets folder, and inside assets, create another folder called data (this is a good practice, but you don't need to do that), and place the JSON file inside of it.

Then, in your service, inject the HttpClient (as you already did), and create a method like this:

getData() {
    return this.http
      .get<any>('assets/data/yourFileName.json')
      .toPromise()
      .then(res => res.data)
      .then(data => {
        return data;
      });
  }

And call it where you need it. Something to help you in case you need it:

ngOnInit(): void {
    this.myService
      .getData()
      .then(foo => (this.myList = foo));
  }
AhmedSHA256
  • 525
  • 2
  • 20
  • Putting the file in `assets` works for me. Is that the only location directly accessible via HTTP? – Vihung Nov 21 '22 at 15:06
  • It is just a convention, a JSON file is an assets, so it is recommended to put that there, but you can put the json file wherever you want as long as you know where it is – AhmedSHA256 Nov 21 '22 at 15:51