8

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 bring each and every key into the html page or how to parse this one using service?

Thanks in advance.

1 Answer 1

25

You can do so 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 parse through the data

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

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

For promises as in your case modify 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 are getting data and resolving to promise. To use this in html you have to get the data in your component page as follows.

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

You can now use the patdata in your html

<h1> {{patdata | json}} </h1>
Sign up to request clarification or add additional context in comments.

4 Comments

load(){ console.log('json called'); return new Promise(resolve => { this.http.get('assets/data/patient.json').subscribe(response => { this.data = response.json(); console.log("json Data" ); console.log(this.data); this.processData(this.data); console.log(this.data); resolve(this.data); }); }); }
code inside the comment converts your json to promise and then returns the data. While the code i have shared uses observable. You can use either of it based on your need. have a look on the difference between observable and promises before deciding :)
okay its working instead of this.myjsondata = data i use this.patDat = data. then how to bring it to html.
use the second part of my code in yout ts file to use it in html. Instead of keyword "subscribe" use "then" as you are returning promise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.