Angular : Unable to GET local json using HttpClien

2019-04-17 04:43发布

问题:

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"
 ]