如何使用离子2打字稿从本地JSON获取数据到HTML页面 [英] How to get the data from local JSON, to the HTML page using ionic 2 typescript

查看:140
本文介绍了如何使用离子2打字稿从本地JSON获取数据到HTML页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种类型的JSON文件。

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"}
          ]
        }
      ]
    }
  }
}

如何将每一个密钥带入html页面或如何使用服务解析这个密钥?

How to bring each and every key into the html page or how to parse this one using service?

提前致谢。

推荐答案

您可以通过创建服务提供商来实现这一目标

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
  }
}

定义你的服务ts构造函数并调用该方法来解析数据

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;
});

确保在app.module.ts中定义服务提供商

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);
        });
    });
}

您在这里获取数据并解析承诺。要在html中使用它,您必须按如下方式获取组件页面中的数据。

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;
    });

您现在可以在html中使用patdata

You can now use the patdata in your html

<h1> {{patdata | json}} </h1>

这篇关于如何使用离子2打字稿从本地JSON获取数据到HTML页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆