Reputation: 102
I am new to angular and going through pluralsight tutorials, i am stuck at a point and not able to go further, my problem is like i have a json file products.json and i am trying to read from Http get method, the application throwing an exception on console which is mentioned below.
GET http://localhost:4200/api/products.json 404 (Not Found)
below is my app structure
here is my ts code.
import { Injectable } from "@angular/core";
import { IProduct } from "./product";
import { Http, Response } from "@angular/Http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/do";
import "rxjs/add/operator/catch";
@Injectable()
export class ProductService {
private _productUrl: string = "../data/products/products.json";
constructor(private _http: Http){}
getProducts():Observable< IProduct[]> {
return this._http.get("/api/products.json")
.map((response: Response) => <IProduct[]>response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
handleError(error: Response) {
console.log(error);
return Observable.throw(error.json().error || 'system error');
}
}
Please let me know, if i am doing something wrong. thanks in advance!
Upvotes: 1
Views: 2951
Reputation: 359
Move your products.json file to .\src\assets\api\products as the project angular CLI only allows to download content from asset using direct url.
private productUrl = 'assets/api/products/products.json';
Upvotes: 0
Reputation: 180
Out-of-the-box functionality of Angular projects built with the CLI allows for files to be publicly accessible via the assets folder located at /src/assets
. You can configure your project to allow other locations to be publicly accessible by editing the file angular-cli.json
. Find the line assets
and modify it in a way that allows access to the file(s) in question:
"assets": ["assets", "products.json","api/products.json"],
Hope that helps!
Upvotes: 4
Reputation: 19288
If you use the CLI you need to add the api folder to the assets in the angular-cli.json
file
"assets": [
"assets",
"favicon.ico",
"api"
],
Upvotes: 0
Reputation: 4207
It seems that there is no API that expose on /api/products.json
, so you can't access this file on this url.
You can try to access the file directly, with :
this._http.get(_productUrl)
Upvotes: 0