To accomplish this, you can create a service provider
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class customService {
constructor(public http:Http) {}
fetchData() {
return this.http.get("YOUR_PATH_TO_THE_JSON_FILE")
.map((res:Response) => res.json().YOUR_JSON_HEADER); //records in this case
}
}
Include the service in your ts constructor and execute the method to process through the retrieved data
this.customService.fetchData().subscribe((data) => {
console.log("data contents: ", data);
this.myjsondata = data;
});
Ensure to declare the service provider in app.module.ts
If using promises, make modifications in your service as shown below:
load() {
console.log('json request made');
return new Promise(resolve => {
this.http.get('assets/data/patient.json').map(response => {
this.data = response.json();
resolve(this.data);
});
});
}
Here, data is obtained and resolved into a promise. To utilize it in html, obtain the data in your component page like so:
this.customService.load().then((data) => {
console.log("data content: ", data);
this.patdata= data;
});
You can now display the patdata in your html
<h1> {{patdata | json}} </h1>