Darpanjbora
Darpanjbora

Reputation: 173

Error 404 in Angular 4 HTTP Request

I tried searching for answers in the already asked similar questions but failed to resolve the problem

I am new to Angular 4 and trying to make a simple Angular frontend for a hypothetical book store. There is a hard-coded dataset present in the app as books.json. But the problem is every time to try to run it I get the following error:

Error showing in the ChromeSo,  Console

And here's the screenshot of the project directory and the code.

enter image description here

Here is my book.service.ts code :

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { IBook } from './book';
import 'rxjs/add/operator/map';

@Injectable()
export class BookService {

  constructor(private _http: Http){}

  getBooks(): Observable<IBook[]> {
    return this._http
    .get("api/books/books.json")
    .map((response : Response) => {
      return response.json() as IBook[];
    });
  }
}

Upvotes: 0

Views: 774

Answers (3)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

move your api folder under root folder. In this case under book-store.

The issue was not in the code. its about finding the path to the json file is invalid

Or

you can keep the files under src folder and add the api into assets in angular-cli.json

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

Upvotes: 2

JasonK
JasonK

Reputation: 5294

One option is to move the json files to the src/assets folder. A better solution would be to edit angular-cli.json and add your folder (route) to apps.assets:

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

Now the json files should be accessible, you don't need to change any code. Don't forget to stop serving the application and run ng serve again.

Upvotes: 3

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

Your folder structure seems ok. The problem is that your server does not know anything about api folder. In your .angular-cli.json, put "api" to your assets array like following

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

Upvotes: 1

Related Questions