Reputation: 115
I am totally new in angular 4 and trying to call web api httpGet method. I create a json file named student.json . When I run my code in console I can see below Error :
http://localhost:4200/src/data/students.json 404 (Not Found)
My Code :
fetchData(){
this.http.get("src/data/students.json").subscribe(
(data)=>console.log(data)
);
}
What am I wrong? Thanks in advance.
Upvotes: 0
Views: 2012
Reputation: 3
use below code in your service
export class MyDataService {
constructor(private http: Http) { }
fetchData() {
this.http.get('../assets/data/students.json').subscribe(
(data)=>console.log(data)
);
}
}
Upvotes: 0
Reputation: 6383
When you run ng build
, go to dist
and notice your .json file is not there.
This is the reason why it is not being served, the webpack bundle is not adding that data folder, thus the app cannot find your file.
One way to get this to work, is to place your data folder in the assets folder:
src/assets/data/students.json
Then if you run ng build
, notice the assets are available now, and your students.json
is available as well.
By doing that, then ng serve
will get what you want. Keep in mind, the .get is relative from your component. So for example, if I had that code in src/app/app.component.ts
, I'd tell it to go back one level to src
, then enter assets
and finally read data/students.json
, having a relative path ../assets/data/students.json
In the code, like this:
export class AppComponent {
title = 'app';
constructor(private _http: Http) {
this._http.get('../assets/data/students.json').subscribe(
(data)=>console.log(data.json())
);
}
}
Hope this is of help.
Note: I mention ng build
here just to display that src/data
is not available and why it is not working. You don't really need ng build
, ng serve
is just enough.
Upvotes: 4