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?
CodePudding user response:
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);
}
}
CodePudding user response:
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));
}