Angular : Unable to GET local json using HttpClient

試著忘記壹切 提交于 2020-01-01 21:09:28

问题


I am using the latest HttpClient component provided in Angular5 to make a get request for local json but I am getting 404 ever since. I have already imported HttpClientModule module in my app.module.ts.

Snapshot of folder structure:

I am making the call from blog-detail component for blog-list.json. Here is my code:

  constructor(private http: HttpClient) {
  }

  ngOnInit(): void {
    // this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe((data:Blog[]) => {
    this.http.get('app/api/blog-list.json').subscribe((data:Blog[]) => {
         this.blogs = data;
    });
  }

I get following error:

GET http://localhost:909/app/api/blog-list.json 404 (Not Found)

Even if I try to open the file in browser directly by hitting http://localhost:909/src/app/api/blog-list.json I get the application served there instead of the json file.

Please note that the commented request to a rest api on web is successful but fails for call only to a local json file.


回答1:


I was able to fix this but its kinda weird that why it happened at the first place.

For this I had to update the .angular-cli.json and add the path to api folder in assets property. Now the assets property looks like:

"assets": [
    "assets",
    "app/api",
    "favicon.ico"
 ]


来源:https://stackoverflow.com/questions/47768897/angular-unable-to-get-local-json-using-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!