Manu
Manu

Reputation: 10934

Angular : Unable to GET local json using HttpClient

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:

enter image description here

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.

Upvotes: 2

Views: 5411

Answers (1)

Manu
Manu

Reputation: 10934

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

Upvotes: 6

Related Questions