Reputation: 291
In my Angular2 application the organization of the folders is as below
Project
|
+-- file 1
|
+-- api //folder
| |
| | +-- listOfProducts //folder
| |
+-- products.json //file
+-- src //folder
| |
+ | +-- app //folder
| +-- product //folder
+-- product.service.ts
+-- product-list.component.ts
+-- //other files
product.service.ts is as below:
import {Injectable} from '@angular/core';
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';
import {IProduct} from './product';
@Injectable()
export class ProductService{
private _productUrl = 'api/listOfProducts/products.json';
// here 404 error
constructor(private _http: Http) {}
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data=>console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || "Server error");
}
}
Now after I run my application I got the following error
GET http://localhost:4200/api/listOfProducts/products.json 404 (Not Found)
I am aware the problem is that the path directory is typed wrong but I have tried several paths and still could not resolved my problem. The problem is that I have not still the knowledge how the Angular2 read the files. From the root and below or from the file you are and above?
Upvotes: 1
Views: 17961
Reputation: 1
In Devlopment environment keep All json files under assets folder. otherwise you would get 404 file not found error.
Upvotes: 0
Reputation: 1549
If you are using Angular CLI and ng serve to run the angular application, All json files should be under assets folder.
Upvotes: 7
Reputation: 5384
Organisation your project has nothing to do with it, because files should be accessible from the server. It is important how the structure your dist folder looks like. Make sure that dist folder (which is located on your live-server) contains your json files. If not, you need to configure webpack.
Personally, I think that better solution is to keep mock-data inside src catalog f.e. with other assets, in this way:
src
|
+- app
|
+- assets
|
+- css
|
+- img
|
+- mock-data
|
your.json
Upvotes: 15