How to fetch JSON file in Angular 2
Keep the json file in Assets (parallel to app dir) directory
Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:
::app/services/myservice.ts
getOrderSummary(): Observable {
// get users from api
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Here is a part of my code that parse JSON, it may be helpful for you:
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class AppServices{
constructor(private http: Http) {
var obj;
this.getJSON().subscribe(data => obj=data, error => console.log(error));
}
public getJSON(): Observable<any> {
return this.http.get("./file.json")
.map((res:any) => res.json())
.catch((error:any) => console.log(error));
}
}