How to fetch JSON file in Angular 2
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)); }}
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);}
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
return this.http.get('<json file path inside assets folder>.json')) .map((response: Response) => { console.log("mock data" + response.json()); return response.json(); } ) .catch(this.handleError);}
Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.