I am creating an application in angular 2. I am trying to access the json data via http in a service. But i am getting an error saying that
**GET http://localhost:4200/data/products.json 404 (Not Found)**
I have the data in the specified folder but i am unable to access it.
My service code is as follows.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { Item } from './item';
@Injectable()
export class ItemService {
observableItems: Observable<Item[]>
allItems: Item[] = [];
selectedItems: Item[] = [];
errorMessage: string;
url = "http://localhost:4200/data/products.json";
constructor(private http:Http) {
this.observableItems = this.http.get(this.url).map((res: Response) => res.json());
this.observableItems.subscribe(
data => this.allItems = data,
error => this.errorMessage = <any>error);
}
getItems(): Observable<Item[]> {
return this.observableItems;
}
getSelectedItems(): Item[] {
return this.selectedItems;
}
addItem(id:number): void {
let item = this.allItems.find(ob => ob.id === id);
if (this.selectedItems.indexOf(item) < 0) {
this.selectedItems.push(item);
}
}
removeItem(id:number): void {
let item = this.selectedItems.find(ob => ob.id === id);
let itemIndex = this.selectedItems.indexOf(item);
this.selectedItems.splice(itemIndex, 1);
}
}
My html files are in
"Project/src/app/..."
So to access JSON File I need to come back from tabs folder and app folder to reach the base directory for both code and images. I used ../ to come back from a folder.
From this my url in the service will be as follows:
url = "../../assets/data/products.json";