product.service.ts file :
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 { IProduct } from './product';
@Injectable()
export class ProductService {
private _producturl='src/products.json';
constructor(private _http: Http){}
getproducts(): Observable<IProduct[]> {
return this._http.get(this._producturl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log(JSON.stringify(data)));
}
}
Please find the attached screenshot below for folder structure
but when the page loads it shows me an error : zone.js:2744 GET http://0.0.0.0:4200/src/products.json 404 (Not Found)
You need to save your json
file in assets folder, and access from there like this
export class ProductService {
private _producturl='./assets/products.json';
constructor(private _http: Http){}
.........
}
If you using Angular Cli you need to Keep the json file inside Assets folder (parallel to app dir) directory as per official docs.