How to get data from local JSON to an HTML page using ionic 2 typescript

I have this type of JSON file.

{ "records": { "patients": { "day": "Today", "details": [ { "name":"Diab", "stat":"Pending", "phno":"8197246465", "patNames":"Sandra Adams", "tests": [ {"name":"MCHC","result":"positive"} ] } ] } } } 

How to transfer each key to an html page or how to parse it using a service?

Thanks in advance.

+7
angular typescript ionic2
source share
1 answer

You can do this by creating a service provider.

 import {Injectable} from '@angular/core'; import {Http, Response} from '@angular/http'; import 'rxjs/Rx'; @Injectable() export class yourService { constructor(public http:Http) {} getData() { return this.http.get("YOUR_PATH_TO_THE_JSON_FILE") .map((res:Response) => res.json().YOUR_JSON_HEADER); //records in this case } } 

Define the service in your ts constructor and call the method to analyze the data

 this.yourService.getData().subscribe((data) => { console.log("what is in the data ", data); this.myjsondata = data; }); 

Be sure to define the service provider in app.module.ts

For promises, as in your case, change the code as follows: In your service.

 load() { console.log('json called'); return new Promise(resolve => { this.http.get('assets/data/patient.json').map(response => { this.data = response.json(); resolve(this.data); }); }); } 

Here you get the data and decide to promise. To use this in html, you should get the data on your component page as follows.

 this.yourService.load().then((data) => { console.log("what is in the data ", data); this.patdata= data; }); 

Now you can use patdata in your html

 <h1> {{patdata | json}} </h1> 
+22
source share

All Articles